Default and Static Methods in Interfaces

In Java, starting from version 8, interfaces can contain default and static methods. These additions enhance the flexibility and extensibility of interfaces without breaking existing implementations.

Regular Method:

A regular method in an interface is an abstract method that must be implemented by any class that implements the interface. It provides a way to define behavior that all implementing classes must have.


public interface MyInterface {

  // Regular abstract method
  void regularMethod();

}

Default Method:

A default method in an interface is a method that provides a default implementation. It allows adding new methods to interfaces without forcing existing classes to implement them. Classes can choose to override default methods.


public interface MyInterface {

  // Regular abstract method
  void regularMethod();

  // Default method with a default implementation
  default void defaultMethod() {
    System.out.println("Default method implementation");
  }

}

Static Method:

A static method in an interface is a method associated with the interface itself, not with instances of implementing classes. It provides a way to organize utility methods related to the interface without the need for an instance.


public interface MyInterface {

  // Regular abstract method
  void regularMethod();

  // Static method
  static void staticMethod() {
    System.out.println("Static method implementation");
  }

}

Implementing the Interface:

Now, let's create a class that implements the MyInterface interface and provides implementations for the methods.


public class MyClass implements MyInterface {

  // Implementing the regular method
  public void regularMethod() {
    System.out.println("Executing regular method");
  }

  // No need to implement the default method (inherited)

}

Using Static Method:

To use the static method from the interface, you can call it using the interface name.


public class Main {

  public static void main(String[] args) {
    MyInterface.staticMethod();
  }

}

Note:

Default and static methods in interfaces provide a powerful mechanism to extend interfaces without breaking existing code. They offer a flexible way to organize and add functionality to interfaces in a backward-compatible manner.