Video in progress
Why were default methods added to interfaces, and what happens if two interfaces have the same default method?
Default methods (Java 8) were added so you can add a new method to an old interface without breaking the classes that implement it. If two interfaces have a default method with the same signature, the class must override it itself and, if needed, pick with InterfaceName.super.method().
📖 Answer
The history: stream() had to be added to the Collection interface. If it had been added as an abstract method, every Collection implementation in the world would have stopped compiling. A default method comes with a ready-made body.
interface Greeter {
String name();
default String greet() { return "Salom, " + name(); }
}
The "diamond" problem:
interface A { default String hello() { return "A"; } }
interface B { default String hello() { return "B"; } }
class C implements A, B {
@Override
public String hello() { // required, otherwise a compile error
return A.super.hello() + B.super.hello();
}
}
The resolution rules:
- a method in the class or its superclass always wins over a default in an interface;
- the more specific interface (the one that extends the other) wins;
- if it can't be decided, the class overrides it itself.
But: default methods can't hold state (there are no instance fields in an interface), and building complex "multiple inheritance" logic through them makes code confusing. They're best for API evolution and small convenience methods.
Sign up to mark studied questions and save your progress.