Interface in Java

An interface is a collection of abstract methods that define a set of capabilities that a class can implement. Interfaces can be used to define a contract that a class must adhere to or to provide a set of capabilities that can be used by multiple classes. In this tutorial, we will provide an example of how to create and use an interface in Java.

Creating an Interface in Java

To create an interface in Java, you need to use the interface keyword in the interface declaration. Here is an example of an interface:

public interface Shape {
   public double getArea();
   public double getPerimeter();
}

In this example, we have created an interface called Shape. The Shape interface defines two abstract methods: getArea and getPerimeter. Any class that implements the Shape interface must provide an implementation for these methods.

Using an Interface in Java

To use an interface in Java, you need to create a class that implements the interface and provides an implementation for all of the abstract methods defined in the interface. Here is an example of a class that implements the Shape interface:

public class Rectangle implements Shape {
   private double length;
   private double width;

   public Rectangle(double length, double width) {
      this.length = length;
      this.width = width;
   }

   public double getArea() {
      return length * width;
   }

   public double getPerimeter() {
      return 2 * (length + width);
   }
}

In this example, we have created a class called Rectangle that implements the Shape interface. The Rectangle class has two instance variables called length and width and a constructor that takes these two values as parameters.

The Rectangle class provides an implementation for the getArea and getPerimeter methods defined in the Shape interface. The getArea method returns the area of the rectangle, and the getPerimeter method returns the perimeter of the rectangle.

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author