Java interfaces vs abstract classes: when to use which
What interfaces and abstract classes are each for, default methods, composition over inheritance, and how interfaces make Java code easy to test.
Both interfaces and abstract classes let you write code against a general type and plug in specific implementations. They solve different problems, though.
Interfaces describe a capability
public interface Notifier {
void send(String patientId, String message);
}
public class SmsNotifier implements Notifier { /* … */ }
public class EmailNotifier implements Notifier { /* … */ }The booking code depends only on Notifier. It doesn't know or care how messages are delivered,
and a class can implement as many interfaces as it needs (Comparable, AutoCloseable, …).
Since Java 8, interfaces can have default methods (behaviour shared by all implementers) and static methods:
public interface Notifier {
void send(String patientId, String message);
default void sendAll(List<String> patientIds, String message) {
for (String id : patientIds) send(id, message);
}
}Interfaces can't hold instance fields, only constants.
Abstract classes share state and code
public abstract class Appointment {
protected final String patientId;
protected final LocalDateTime start;
protected Appointment(String patientId, LocalDateTime start) {
this.patientId = patientId;
this.start = start;
}
public abstract Duration length(); // each kind decides
public LocalDateTime end() { // shared logic
return start.plus(length());
}
}
public class CheckUp extends Appointment {
public CheckUp(String id, LocalDateTime start) { super(id, start); }
@Override public Duration length() { return Duration.ofMinutes(20); }
}An abstract class can have fields, constructors and partly-implemented methods. A class can extend only one class.
Choosing
| Question | Interface | Abstract class |
|---|---|---|
| Unrelated classes share a behaviour? | ✓ | |
| Implementations share fields and a constructor? | ✓ | |
| A class needs several of these? | ✓ | |
| You want lambdas to implement it (one abstract method)? | ✓ |
Rule of thumb: start with an interface. Add an abstract base class later if implementations end up duplicating state and code.
Composition over inheritance
Deep inheritance chains are hard to change. Often it's better for a class to hold a collaborator than to be a subtype:
public class Clinic {
private final Notifier notifier; // composed, not inherited
public Clinic(Notifier notifier) { this.notifier = notifier; }
}Interfaces make testing easy
Because Clinic depends on the Notifier interface, a test can pass a fake:
class RecordingNotifier implements Notifier {
final List<String> sent = new ArrayList<>();
public void send(String id, String msg) { sent.add(id + ": " + msg); }
}No SMS gateway needed, and the test can check exactly what was sent.
Interfaces, abstract classes and composition are covered in Java Intermediate.
Questions and answers
- When should I use an abstract class instead of an interface in Java?
- Use an interface to describe a capability that unrelated classes can share. Use an abstract class when closely related classes share state (fields) and implementation, and you want to force a common constructor. When in doubt, start with an interface.
- Can a Java class implement more than one interface?
- Yes, any number. A class can extend only one class, abstract or not. That asymmetry is a big reason interfaces are the default choice for describing behaviour.
Practise it
Read next
- Java equals and hashCode: the contract and why HashMap depends on it
What == really compares, how to write equals and hashCode correctly, why breaking the contract makes HashSet lose objects, and the shortcuts that do it for you.
- Java streams and lambdas: filter, map, collect and groupingBy
Lambdas and method references, the stream pipeline, collecting into lists and maps, groupingBy for reports, Optional, and when a plain loop is clearer.