Default Methods

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Java 8 allows interfaces to have concrete, implemented methods using the default keyword.
  • This feature was introduced to provide Backward Compatibility.
  • It allows API designers to add new methods to existing interfaces without breaking all the older classes that implement them.

Concept

For 20 years, interfaces in Java could only contain abstract methods. If you added a new method to the java.util.Collection interface, millions of Java applications worldwide would instantly fail to compile, because every single custom collection class would be missing the implementation for the new method.

When Java 8 introduced Streams and Lambdas, they needed to add methods like stream() and forEach() to the Collection interfaces. To do this without breaking the world, they invented Default Methods.

A default method provides a fallback implementation. If a class implements the interface but doesn’t override the method, it inherits the default behavior automatically.

Examples

interface Vehicle {
    void startEngine(); // Abstract method (must be implemented)
    
    // Default method (implementation provided)
    default void honkHorn() {
        System.out.println("Beep beep!");
    }
}

class Car implements Vehicle {
    @Override
    public void startEngine() {
        System.out.println("Car engine started.");
    }
    
    // Notice we DO NOT have to implement honkHorn()
}

public class DefaultMethodExample {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.startEngine();
        
        // We can use the default method inherited from the interface
        myCar.honkHorn(); 
    }
}

Interview Questions

Q: What happens if a class implements two interfaces that both have a default method with the exact same signature?
A: This is known as the Diamond Problem of multiple inheritance. The compiler will immediately throw an error because it doesn’t know which default implementation to inherit.
To resolve this, the class must override the conflicting method and provide its own implementation. Inside that overridden method, you can optionally choose to call one of the interface implementations using InterfaceName.super.methodName().

Q: Can an interface override a method from the Object class with a default method?
A: No. An interface is strictly forbidden from providing default implementations for methods defined in java.lang.Object (like equals(), hashCode(), or toString()). The rule in Java is that classes always win over interfaces. Since every object already inherits these methods from the Object class, an interface default method would never be invoked anyway, so the compiler rejects it.