What are default and static methods in interfaces, and why were they added in Java 8?

8 minintermediatedefault-methodsinterfacejava8

Quick Answer

Default methods provide a method body directly in an interface that implementing classes inherit unless they override it; static methods belong to the interface itself and are called via the interface name. Both were added in Java 8 primarily to let the JDK evolve interfaces like Collection/List (adding stream(), forEach()) without breaking every existing implementation.

Detailed Answer

Before Java 8, adding a new method to an interface broke every class implementing it (a compile error for missing implementations). Default methods solve this by letting an interface provide a body that implementers inherit automatically:

interface Vehicle {
    void drive();
    default void honk() { System.out.println("Beep!"); } // inherited by default
}
class Car implements Vehicle {
    public void drive() { /* ... */ } // honk() comes for free
}

A class can still override a default method if it needs different behavior. If a class implements two interfaces with clashing default methods, the compiler forces it to explicitly resolve the conflict by overriding the method itself.

Static interface methods belong to the interface type, not to instances, and are called like InterfaceName.method() — used for factory/helper methods related to the interface (e.g., Comparator.comparing(...), List.of(...)):

interface MathOps {
    static int square(int x) { return x * x; }
}
MathOps.square(5); // 25

The main motivation was API evolution: default methods let the JDK retrofit Collection/List/Map with forEach, stream, removeIf, getOrDefault, etc., in Java 8 without breaking the huge ecosystem of existing implementations — a form of controlled, backward-compatible multiple inheritance of behavior (not state).