What is a default method in an interface, and why was it added to Java?
A default method is a method with a body inside an interface. The classes that implement the interface get the body for free unless they write their own.
public class Main {
public static void main(String[] args) {
Notifier n = new EmailNotifier();
n.notify("build done");
}
}
And here is the interface with the default method.
public interface Notifier {
void send(String message);
// A default method. Every implementation gets this
// unless it writes its own.
default void notify(String message) {
send("NOTICE: " + message);
}
}
public class EmailNotifier implements Notifier {
@Override
public void send(String message) {
System.out.println("email: " + message);
}
}
And why was it added to Java? For one big reason. It was the change that made it possible to add methods to an existing interface without breaking the classes that implement it.
the problem before Java 8 the fix
--------------------------------- --------------------------------------------
you cannot add a method to an the default method has a body,
interface without breaking every so the old classes still work
class that implements it
And there is a second reason, and it is about the code that was being copied into every implementation. So if three classes all had the same four lines, the default method puts those four lines in the interface once.
public interface Validator {
boolean isValid(String value);
default boolean isValidOrEmpty(String value) {
return value == null || value.isBlank() || isValid(value);
}
}
And there is a third thing that is worth knowing about. An interface can also have static methods, and those belong to the interface itself and are not inherited. So they are a place for a factory or a helper that belongs with the contract.
public interface PaymentMethod {
boolean pay(double amount);
// A static method. It belongs to the interface and is
// not inherited by the implementations.
static PaymentMethod of(String kind) {
if ("card".equals(kind)) {
return new CardPayment("default", 1000);
}
return new WalletPayment("default");
}
}
So the rule to remember is this. A default method has a body, and it lets an interface grow without breaking the classes that implement it.
The last question in this topic is about when to use one and what problems it causes.