All topics
library
intermediate

Diamond Problem & Default Methods in Interfaces

Understand how Java resolves conflicts when a class inherits the same default method from multiple interfaces.

Java 8 introduced default methods in interfaces — methods with implementations that don't require implementing classes to override them.

Default methods = an apartment building providing default furniture. Tenant (class) can keep the default or bring their own (override). Diamond problem = two building managers giving different default furniture — tenant must pick which to keep.

Key Concepts

1
The diamond problem: if a class implements two interfaces that both have a default method with the same signature, which one wins?
2
Resolution rules: 1. Class wins: if the class (or superclass) provides the method, it takes priority over any default method 2. Most specific interface wins: if interface B extends A and both have the default, B's version wins 3. Explicit resolution required: if neither rule resolves the conflict, the class MUST override and explicitly choose
3
Explicit resolution syntax: @Override void method() { InterfaceA.super.method(); // explicitly call A's default }
4
Default methods were added to evolve interfaces without breaking existing implementations. Key examples: - List.sort() — added in Java 8 without breaking existing List implementations - Collection.stream() — added streaming without changing every collection - Iterator.forEachRemaining() — default implementation using hasNext/next - Map.getOrDefault(), Map.computeIfAbsent() — added in Java 8
5
Static methods in interfaces (Java 8) and private methods (Java 9) further enhanced interface capabilities.