Interface Default Methods
TL;DR
- Default Methods (introduced in Java 8) allow interfaces to have methods with concrete implementation bodies.
- They were introduced primarily to support backward compatibility when adding new features (like Streams and Lambdas) to existing interfaces (like
Collection). - You define them using the
defaultkeyword.
Concept
Before Java 8, interfaces could only contain abstract methods. If you published a library with interface Vehicle, and 10,000 developers implemented it, you were stuck. If you tried to add a new startRadio() method to Vehicle in v2.0, you would instantly break the code of all 10,000 developers, because their classes wouldn’t implement the new method.
Java 8 solved this by allowing default methods. You can add default void startRadio() { System.out.println("Playing music"); } to the interface. Now, all 10,000 existing classes automatically inherit this behavior without breaking, but they can still optionally @Override it if they want.
Examples
public interface Vehicle {
// Abstract method (must be implemented by classes)
void drive();
// Default method (already implemented!)
default void honk() {
System.out.println("Beep beep!");
}
}
// Car does not need to implement honk(), it inherits it automatically!
public class Car implements Vehicle {
@Override
public void drive() {
System.out.println("Driving a car");
}
public static void main(String[] args) {
Car myCar = new Car();
myCar.drive();
myCar.honk(); // Outputs: Beep beep!
}
}
Interview Questions
Q: What happens if a class implements two interfaces that have the exact same default method?
A: This is the famous Diamond Problem of multiple inheritance.
If interface A has default void fly() and interface B has default void fly(), and a class implements both, the Java compiler will throw an error: “class inherits unrelated defaults for fly()”.
To resolve this, the class must override the fly() method explicitly to resolve the ambiguity. Inside the overridden method, you can optionally call a specific interface’s implementation using A.super.fly();.
Q: Can a default method override a method from the Object class?
A: No. An interface cannot provide a default implementation for methods like equals(), hashCode(), or toString(). If you try, it will result in a compile-time error. The rule is that classes always win over interfaces. Since every class inherently extends Object, any default method trying to override Object would be completely useless because the Object class’s implementation would always take precedence anyway.