All 15 Interfaces & Abstract Classes questions
More in Interfaces & Abstract Classes
Advertisement
Back to results for “OOP & Classes”
Java › Interfaces & Abstract Classes

How is the 'diamond problem' (a class implementing two interfaces with conflicting default methods) resolved in Java, and what rule determines which default method 'wins' or whether the compiler requires explicit resolution?

Advanced

Answer

If a class implements two interfaces that both declare a default method with the same signature, and NEITHER interface is a subtype of the other, the compiler forces the implementing class to explicitly override that method itself (resolving the ambiguity manually, often by explicitly choosing which interface's version to delegate to via InterfaceName.super.methodName()), refusing to guess which one should 'win' -- however, if one interface is a subtype of the other (extends it), the more specific (subtype) interface's default method automatically takes precedence without requiring any explicit resolution, following a 'most specific wins' rule similar in spirit to how class inheritance resolves method overriding.
public interface A { default void greet() { System.out.println("Hello from A"); } }
public interface B { default void greet() { System.out.println("Hello from B"); } }

public class C implements A, B {
    // MUST override greet() explicitly -- compiler can't choose between A and B's versions
    @Override
    public void greet() {
        A.super.greet();  // explicitly choose A's version (or B's, or provide entirely new logic)
    }
}
Real-world example A class implementing two independent library interfaces that happen to both define a default log() method with the same signature is forced by the compiler to explicitly resolve the conflict, choosing to delegate to one specific interface's implementation via the InterfaceName.super.method() syntax, making the ambiguity resolution deliberate and visible in the source code rather than an implicit, potentially surprising choice.

Common follow-ups: How does this differ from the classic C++ 'diamond problem' with multiple class inheritance, which Java's single-class-inheritance design was originally intended to avoid entirely?;What happens if interface A extends interface B, and both declare the same default method -- does the compiler still force explicit resolution?