Java - OOP - Interface

Java Interface is a way to achieve abstraction in Java. It allows you to define a set of abstract methods that can be implemented by any class that implements the interface. An interface in Java is a collection of abstract methods and constants. It is used to define a set of rules or contract that must be followed by any class that implements the interface.

When to use an interface in Java:

  • When you want to define a set of methods that should be implemented by any class that implements the interface.
  • When you want to provide a common behavior for a group of classes.
  • When you want to achieve loose coupling between classes.

Points to remember about Java Interface:

  • An interface can only contain abstract methods and constants. It cannot have any concrete methods.
  • An interface is declared using the "interface" keyword in Java.
  • A class can implement multiple interfaces in Java.
  • An interface cannot be instantiated directly. It can only be implemented by a class.
  • All the methods in an interface are by default public and abstract.
  • All the variables in an interface are by default public, static and final.
// Declare the interface
interface Shape {
   double area(); // Abstract method
}

// Implement the interface
class Circle implements Shape {
   private double radius;

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

   public double area() {
      return Math.PI * radius * radius;
   }
}

// Implement the interface
class Rectangle implements Shape {
   private double width;
   private double height;

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

   public double area() {
      return width * height;
   }
}

// Use the interface
public class Main {
   public static void main(String[] args) {
      Shape circle = new Circle(5);
      Shape rectangle = new Rectangle(10, 5);
      System.out.println("Area of circle: " + circle.area());
      System.out.println("Area of rectangle: " + rectangle.area());
   }
}

In the above example, we have declared an interface called "Shape" which contains an abstract method called "area()". We have then implemented this interface in two classes - "Circle" and "Rectangle". Both of these classes have implemented the "area()" method according to their respective formulas. Finally, we have used these classes by creating objects of the "Circle" and "Rectangle" classes and calling their "area()" methods using the interface reference. This allows us to achieve polymorphism and loose coupling between the classes.