Card 05/ 08

ConceptDifficulty: Advanced1 min

default Methods, and the Problem They Were Added to Solve

Java 8 wanted to add forEach to List. Adding a method to an interface used to break every class implementing it, and there were millions of them in code nobody at Oracle could edit.

A default method is a method in an interface with a body. Classes that already implement the interface get it for free and keep compiling; classes that want something different override it.

java
interface Archivable {
    String archiveKey();
    LocalDate archivedOn();

    default boolean isExpired() {
        return archivedOn().isBefore(LocalDate.now().minusYears(7));
    }
}

The default body may only use the interface's own methods, because an interface still has no fields to read. That is the line between a default method and an abstract class, and it has not moved.

The three kinds of method an interface may declare
KindHas a bodyOverridableSince
AbstractNoMust be implementedJava 1
defaultYesYesJava 8
staticYesNo — called on the interface nameJava 8
privateYesNo — helper for the two aboveJava 9

So an interface can now carry behaviour without carrying data, which is what makes it possible to grow one without breaking its implementations. Use it for that — a default that most classes want — rather than as a way to avoid writing an abstract class.