Card 05/ 08
All 8 cards
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.
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.
| Kind | Has a body | Overridable | Since |
|---|---|---|---|
| Abstract | No | Must be implemented | Java 1 |
default | Yes | Yes | Java 8 |
static | Yes | No — called on the interface name | Java 8 |
private | Yes | No — helper for the two above | Java 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.