All 15 Interfaces & Abstract Classes questions
More in Interfaces & Abstract Classes
Advertisement
Back to results for “OOP”
Java › Interfaces & Abstract Classes

How do default methods (introduced in Java 8) let an interface provide a method implementation, and what problem were they specifically introduced to solve?

Intermediate

Answer

A default method (marked with the default keyword) provides a concrete implementation directly within an interface, which implementing classes inherit automatically unless they choose to override it -- this was specifically introduced to solve the 'interface evolution' problem: before Java 8, adding a new method to an existing, widely-implemented interface would break EVERY existing implementing class (since they'd all suddenly fail to compile, missing the newly-required method), whereas a default method lets a new method be added to an interface without breaking any existing implementations, which is precisely how the JDK itself was able to add substantial new functionality (like Collection's forEach() and removeIf() default methods) to interfaces already implemented by countless existing classes across the ecosystem, without breaking backward compatibility.
public interface Vehicle {
    void move();

    default void honk() {  // added in a later version WITHOUT breaking existing implementers
        System.out.println("Beep!");
    }
}

public class Car implements Vehicle {
    public void move() { System.out.println("Driving"); }
    // honk() is inherited automatically -- Car doesn't need to implement it, and compiles fine
}
Real-world example The JDK added a forEach(Consumer<T> action) default method directly to the Iterable interface in Java 8, instantly giving every single existing class across the entire Java ecosystem that already implemented Iterable (written years before Java 8 existed) this new capability automatically, without requiring any of those classes to be modified or recompiled.

Common follow-ups: What happens if a class implements two interfaces that both provide a default method with the identical signature -- how is the conflict resolved?;Can a default method access the implementing class's own private fields?