Explain the diamond problem with interfaces and how Java resolves it.

8 minadvanceddiamond-problemdefault-methodsinterface

Quick Answer

The diamond problem arises when a class implements two interfaces that each provide a conflicting default method with the same signature — the compiler can't pick one automatically. Java resolves it by refusing to compile until the implementing class explicitly overrides the method, optionally calling a specific parent's version via InterfaceName.super.method().

Detailed Answer

The classic "diamond problem" happens when a class inherits the same method signature from two different sources that each provide a default implementation, and it's ambiguous which one should apply. In Java, this can only arise through default methods on interfaces (since classes only support single inheritance, and abstract methods without bodies never conflict):

interface A { default String name() { return "A"; } }
interface B { default String name() { return "B"; } }

class C implements A, B {
    // compile error unless C overrides name() explicitly
}

Java doesn't guess — it forces the implementing class to resolve the conflict explicitly by overriding the method, optionally delegating to one of the parent interfaces using InterfaceName.super.method():

class C implements A, B {
    @Override
    public String name() {
        return A.super.name() + B.super.name(); // explicit choice
    }
}

If a class extends both a concrete superclass and implements an interface with a default method of the same signature, the class (superclass) implementation always wins — "class wins over interface" is one of Java's tie-breaking rules, so no ambiguity error is raised in that specific case.

This design avoids the classic C++ diamond-inheritance ambiguity around state entirely (Java still forbids multiple inheritance of instance fields/constructors), while allowing controlled multiple inheritance of behavior through default methods.