What is a default method in an interface, and why was it added to Java?
A default method is a method with a body declared in an interface. The implementor inherits it and does not have to write it, but it may override it. A static method in an interface is also allowed, and a private helper method for the interface's own default methods can be declared too.
public class Main {
public static void main(String[] args) {
Notifier n = new EmailNotifier();
n.notify("build done");
}
}
interface Notifier {
void notify(String message);
default void notifyWithPrefix(String message) {
notify("[system] " + message);
}
}
class EmailNotifier implements Notifier {
public void notify(String message) { System.out.println("email: " + message); }
}The example shows the inheritance in action. The email notifier only implements the abstract notify method, yet it can be asked to send a prefixed notification, because notifyWithPrefix has a default implementation that calls notify with a prefix applied. The output shows the message arriving with the prefix in place.
Default methods were added mainly for evolvability. Before them, adding a method to an interface broke every implementor in every codebase, including third-party libraries. With a default method, existing implementors inherit sensible behaviour and keep compiling, so an interface can grow without a flag day.
The trade-off is that default methods weaken the guarantee. The interface no longer guarantees that every implementor has its own behaviour, so a caller cannot assume the default is what will run. And if two interfaces supply the same default, the implementing class has to resolve the conflict. That is why defaults work best for behaviour that genuinely has one sensible default, such as a convenience method built on other contract methods.