library
intermediateDefault & Static Methods in Interfaces
Understand why Java 8 added default methods, how they enable interface evolution, and resolution rules for conflicts.
Default methods (Java 8) let interfaces provide method implementations. Static methods let interfaces define utility methods. Both were added primarily to evolve the Collections API without breaking existing implementations.
Default method = a recipe included with a kitchen appliance. You can use it as-is or customize it. The appliance (interface) provides a starting point without forcing every chef (implementor) to write the recipe from scratch.
Key Concepts
1
Default methods:
- Declared with the default keyword in an interface
- Implementing classes inherit the default but can override it
- Enable interface evolution: adding a default method doesn't break existing implementations
- Don't break the 'functional interface' contract: a functional interface can have multiple defaults
2
Conflict resolution rules:
1. Class wins: a method in a class (or abstract class) takes priority over any interface default
2. More specific interface wins: if interface B extends interface A and both have the same default, B's version wins
3. Ambiguity: if a class implements two unrelated interfaces with the same default method, the class MUST override to resolve
3
Static methods:
- Declared with static in an interface
- Cannot be overridden or inherited — called only as InterfaceName.method()
- Useful for factory methods: List.of(), Map.entry()
- Cannot access instance methods or fields
4
Private methods (Java 9) allow interfaces to share code between default methods without exposing it publicly.