When a class implements multiple interfaces that provide the same method signature, Java requires the implementing class to be explicit about which implementation to use to avoid the 'diamond problem'.
- Conflict Resolution: If two interfaces specify the same method signature, the implementing class must provide its own implementation, even if one of the interfaces provides a default implementation. You can delegate to a specific interface's default method using
InterfaceName.super.methodName(). - Class Priority: If a class inherits a method from a superclass and also implements an interface with a default method of the same signature, the superclass implementation always takes priority.
public interface InterfaceA {
public abstract void doSomething();
}
public interface InterfaceB {
public default void doSomething() {
System.out.println("test");
};
}
public class Class implements InterfaceA, InterfaceB {
// Compiler forces an implementation because of the conflict
@Override
public void doSomething() {
// Delegate to the behavior specified in InterfaceB
InterfaceB.super.doSomething();
}
}