Java 8 introduces a new feature called Default Interface. This feature allows interface creator to provide default implementations for methods, so that concrete classes that implementing the interface don’t have to provide implementations for those methods.
The below code gives you an example of how to create default interface and how to use them.
Interface
package Core.Default;
public interface Interface1 {
public void displayImplSpecific();
public default void displayDefault() {
System.out.println("Interface Specific Display");
}
}
Class Implementing the Interface
package Core.Default;
public class Interface1Impl implements Interface1 {
@Override
public void displayImplSpecific() {
System.out.println("Implementation Specific Display.");
}
}
Main Class
package Core.Default;
public class DefaultDemo1 {
public static void main(String[] args) {
Interface1Impl interface1Impl = new Interface1Impl();
interface1Impl.displayDefault();
interface1Impl.displayImplSpecific();
}
}
Output
Interface Specific Display
Implementation Specific Display.
Explanation
As you can see from the output and main code, the call to displayDefault by interface1Impl instance prints the text “Interface Specific Display”. The concrete class didn’t had to implement displayDefault as it inherited
the default implementation from the interface.