What is the diamond problem, and what happens in Java when a class inherits the same default method through two interfaces?
The diamond problem is the shape where a class inherits the same thing through two paths. In Java, when it happens with interfaces and default methods, you have to say which one you want, or the code does not compile.
public class Main {
public static void main(String[] args) {
C c = new AppConfig();
System.out.println(c.describe());
}
}
And here are the three interfaces and the class.
public interface A {
default String describe() {
return "A";
}
}
public interface B {
default String describe() {
return "B";
}
}
public interface C extends A, B {
// This line is needed. Without it the class will not compile.
@Override
public String describe() {
return A.super.describe();
}
}
So what happens in Java when a class inherits the same default method through two interfaces? The compiler refuses the class. The message says that the class inherits unrelated defaults for the method, so it must override it.
the situation what Java does
------------------------------------- ----------------------------------
two interfaces with the same default the class must override it
method
one interface with the default and the interface wins, no error
one without it
two interfaces with no default no problem at all
And the reason Java allows this is that interfaces do not carry state. There is no field to be copied twice, so the only thing that can clash is a method, and a method clash has an easy answer because the class says which one it wants.
the thing the class version the interface version
----------------- ------------------------- ---------------------------
the state not possible, a class not possible, interfaces
has one parent have no fields
the methods the child overrides the class says which one
And there is a third rule that is worth knowing about, and it is about the priority. If a class extends a superclass that has the method, and it also implements an interface that has the same default method, then the class method wins. So the superclass always beats the interface.
public class AppConfig extends BaseConfig implements A, B {
// The method from BaseConfig is used.
}
So the rule to remember is this. The class has to resolve the clash, and the superclass wins over the interfaces.
The last question in this topic is about resolving an ambiguous method.