How java 8 default method ambiguity solved
Default methods are introduced in Java 8. The main purpose of default method is to make possible evolving an existing API in compatible way. Interfaces can contain method implementation for which implementing class doesn’t need to provide implementation.
public interface A { default boolean someCondition(){ return true; } }
Today we will see how ambiguity is solved when class implements interfaces that have the same default method signature.
There are 3 rules which define the resolution mechanism
1. Method declaration defined in class or superclass wins over the default method declaration.
2. Secondary, the most specific sub-interface which has default method declaration wins
3. If there is still ambiguity, explicitly should be specified which default method implementation to use.
Let’s see in examples
Rule 1
public interface A {
default void printName(){
System.out.println("from A");
}
}
public class D implements A{
public void printName() {
System.out.println("from D");
}
public static void main(String[] args) {
new D().printName();
}
}
//Output: from D
// D
implementations the default method
[addToAppearHere]
Rule 2
public interface A { default void printName(){ System.out.println("from A"); } } public interface B extends A { default void printName() { System.out.println("from B"); } } public class D implements B{ public static void main(String[] args) { new D().printName(); } } //Output: from B // ForD
the most specific sub-interface isB
Rule 3
public interface A {
default void printName(){
System.out.println("from A");
}
}
public interface B {
default void printName() {
System.out.println("from B");
}
}
public class D implements B, A {
public static void main(String[] args) {
new D().printName();
}
public void printName() {
A.super.printName();
}
}
//Output: from A
// Here we have ambiguity, that's why we need to specify explicitly the interface from which to take the implementation.