Video in progress
A class implements two interfaces, and both have a default method with the same signature. What happens and how do you resolve it?
A compile error: the class has to resolve the conflict itself. You override the method in the class and, if needed, call a specific interface's version with InterfaceName.super.method().
📖 Answer
interface Logger {
default String prefix() { return "[LOG]"; }
}
interface Auditor {
default String prefix() { return "[AUDIT]"; }
}
class AuditLogger implements Logger, Auditor {
@Override
public String prefix() {
return Logger.super.prefix() + Auditor.super.prefix(); // we combined both
}
}
Without the override: class AuditLogger inherits unrelated defaults for prefix() from types Logger and Auditor.
Java's rules:
- The class wins. If the parent class (or the class itself) has this method, it always beats an interface default.
- The more specific interface wins. If
B extends Aand both havedefault foo(), theBversion is chosen, with no conflict. - In other cases, the class must make an explicit choice.
Even if one interface has a default and the other an abstract method, the class must override it; the compiler doesn't pick the default automatically.
The X.super.method() syntax works only for directly implemented interfaces.
Sign up to mark studied questions and save your progress.