Sep 14, 2018

Java Default Methods for interfaces

Following your modification by adding new method to the old interface, you would also have to modify the classes that implement the interface by implementing the new method. However, rather than leaving the new method as abstract, you can instead define a default implementation.

You specify that a method definition in an interface is a default method with the default keyword at the beginning of the method signature. All method declarations in an interface, including default methods, are implicitly public, so you can omit the public modifier.
public interface i88caInterface {
   default String myNewMethod() {
      return "Default method is great";
   } 
}
With this interface, you do not have to modify any class that implements the interface. All those classes will have the method myNewMethod already defined.

When you extend an interface that contains a default method, you can do the following:
  1. Not mention the default method at all, which lets your extended interface inherit the default method.
  2. Redeclare the default method, which makes it abstract.
  3. Redefine the default method, which overrides it.
1st case:
public interface i88caExtendedInterface extends i88caInterface { }

Any class that implements the interface i88caExtendedInterface will have the implementation specified by the default method i88caInterface.myNewMethod.

2nd case:
public interface i88caAbstractInterface extends i88caInterface {
   public String myNewMethod();
}
Any class that implements the interface i88caAbstractInterface will have to implement the method myNewMethod; this method is an abstract method like all other nondefault (and nonstatic) methods in an interface.

3rd case:
public interface i88caExtendedInterface extends i88caInterface {
   default public String myNewMethod() {
      return "Extended default method is working";
   } 
}
Any class that implements the interface i88caExtendedInterface will use the implementation of myNewMethod specified by this interface instead of the one specified by the interface i88caInterface.