Easy java java-21

What is the difference between default and static methods in interfaces?

The 30 second answer

A default method has a body inside the interface and is inherited, so implementing classes get it for free but can override it. It was added so the JDK could add methods like forEach to existing interfaces without breaking every implementation. A static interface method belongs only to the interface; you call it through the interface name, and implementing classes don't inherit it.

interface Greeter {
    String name();
    default String greet() { return "Hello, " + name(); }   // inherited, overridable
    static Greeter of(String n) { return () -> n; }          // Greeter.of("Amin")
}

Default methods enabled interface evolution in Java 8: Iterable.forEach, Collection.stream() and Map.getOrDefault were added without breaking existing implementations.

Conflict rules: a method declared in a class wins over a default method. If a class inherits the same default method from two unrelated interfaces, it must override it, and can pick one with A.super.greet().

Static interface methods are not inherited by implementing classes or subinterfaces; you must call them as Greeter.of(...).

Sources: JLS 9.4 Method Declarations, JLS 8.4.8 Inheritance, Overriding, and Hiding

Sources (0)
See inline citations in the answer above.