Video in progress
What does the "composition over inheritance" principle mean?
To reuse behavior, instead of inheriting from a class it's better to hold the object you need as a field and delegate to it. Composition makes coupling looser and lets you swap things at runtime.
📖 Answer
A common mistake with inheritance:
// bad: "Stack is-a Vector", a historical mistake in Java itself
class AuditedList<E> extends ArrayList<E> {
@Override public boolean add(E e) { log(e); return super.add(e); }
// does addAll call add internally? That depends on the ArrayList implementation
}
If the parent class's internal details change, the subclass breaks silently. This is called the "fragile base class" problem.
With composition:
class AuditedList<E> {
private final List<E> inner;
private final AuditLog log;
AuditedList(List<E> inner, AuditLog log) { this.inner = inner; this.log = log; }
void add(E e) { log.write(e); inner.add(e); }
}
Now inner can be an ArrayList or a CopyOnWriteArrayList. Strategy, Decorator and Proxy all rely on this principle.
That doesn't mean inheritance is bad: when there's a real "is-a" relationship and the parent class was designed for inheritance (for example, an abstract class), it has its place.
Sign up to mark studied questions and save your progress.