Java: Inheritance Rules of Default Method in Interface
Prior to Java 8, interfaces were limited to abstract methods only. This required separate classes to implement them. Whenever there a new method is added to the interface, the class must update its code. In order to overcome this, Java 8 introduces default methods, enabling interfaces to have implemented methods without affecting classes that implement the interface.
Hence said, there are certain rules to keep in mind while implementing an interface with default methods. They’re shown below.
Rule 1: Super class method takes priority
If a class extends another class and also implements an interface, the super class and interface’s default methods are of the same signature then the Super class’s method takes priority over an interface's default method.
class Hello {
public void sayIt() {
System.out.println("Hello");
}
}
interface Hi {
default void sayIt() {
System.out.println("Hi");
}
}
class Message extends Hello implements Hi {
public void printMessage() {
sayIt();
}
public static void main(String[] args) {
new Message().printMessage(); // Prints 'Hello'
}
}
Rule 2: Sub Interface takes priority
If two interface A and B have the same default method, and B extends A, then B’s default method takes the priority over A’s default method.
interface Hello {
default void sayIt() {
System.out.println("Hello");
}
}
interface Hi extends Hello {
default void sayIt() {
System.out.println("Hi");
}
}
class Message implements Hi {
public void printMessage() {
sayIt();
}
public static void main(String[] args) {
new Message().printMessage(); // Prints 'Hi'
}
}
Rule 3: Multiple Inheritance rule
If a class implements two interfaces, and those two interfaces have the default method with the same signature, then the class can do one of the two below things to resolve this conflict. Otherwise, the compilation fails.
- Provide its own implementation
- Call to a specific interface’s default method
interface Hello {
default void sayIt() {
System.out.println("Hello");
}
}
interface Hi {
default void sayIt() {
System.out.println("Hi");
}
}
// Compilation FAILS ifthe class doesn't override
class Message implements Hi, Hello {
public static void main(String[] args) {
new Message().sayIt();
}
}
class Message implements Hi, Hello {
@Override
public void sayIt() {
Hi.super.sayIt(); // Call the default method from a specific interface
}
public static void main(String[] args) {
new Message().sayIt(); // Hi
}
}