Java Interfaces

java

In Java, an interface is a reference type that defines a set of methods that a class must implement. An interface is similar to a class, but it does not have any implementation details for its methods. Instead, it serves as a blueprint for a class, specifying the methods that the class must implement.

Interfaces are used to define a common set of methods that can be implemented by multiple classes. This allows you to create a group of related classes that have a common set of methods, but can implement those methods differently.

Here is an example of an interface in Java:

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

In this example, the Shape interface defines two methods: getArea() and getPerimeter(). Any class that implements the Shape interface must provide an implementation for these two methods.

To implement an interface in a class, you use the implements keyword, followed by the name of the interface. For example:

public class Circle implements Shape {
  private double radius;

  public Circle(double radius) {
    this.radius = radius;
  }

  @Override
  public double getArea() {
    return Math.PI * radius * radius;
  }

  @Override
  public double getPerimeter() {
    return 2 * Math.PI * radius;
  }
}

In this example, the Circle class implements the Shape interface and provides an implementation for the getArea() and getPerimeter() methods.

Interfaces are useful because they allow you to create a common set of methods that can be implemented by multiple classes, promoting code reuse and modularity. They also allow you to create flexible and extensible programs, since you can add new functionality by defining new interfaces and implementing them in your classes.