Composition and delegation
suggest changeIn object-oriented programming, composition and delegation are powerful alternatives to class inheritance. The foundational design guideline from the Gang of Four (Design Patterns) states:
"Favor object composition over class inheritance."
While inheritance establishes an "is-a" relationship between classes, composition establishes a "has-a" relationship, and delegation forwards responsibilities from an outer object to an inner worker object.
1. Why Favor Composition Over Inheritance?
Inheritance creates a tight, compile-time coupling between a subclass and its superclass:
- Encapsulation is compromised: Subclasses depend on implementation details of the parent class.
- The Fragile Base Class Problem: If a superclass author modifies an internal method (or adds a new method with the same signature), subclasses may break unexpectedly.
- No dynamic switching: A subclass cannot change its parent type at runtime.
Composition solves these issues by treating other objects as modular components that can be replaced or reconfigured dynamically.
2. Basic Composition and Delegation Example
In delegation, an object contains a reference to another object and forwards specific method calls to it.
import java.util.Objects;
// Component interface
public interface Printer {
void print(String message);
}
// Concrete implementations
public class ConsolePrinter implements Printer {
@Override
public void print(String message) {
System.out.println("[CONSOLE] " + message);
}
}
public class TimestampedPrinter implements Printer {
@Override
public void print(String message) {
System.out.println("[" + java.time.Instant.now() + "] " + message);
}
}
// Composed class that delegates printing
public class DocumentProcessor {
private final Printer printer; // Has-a relationship
// Printer is supplied via composition
public DocumentProcessor(Printer printer) {
this.printer = Objects.requireNonNull(printer, "printer must not be null");
}
public void process(String documentTitle) {
// Core business logic
String result = "Processed: " + documentTitle.toUpperCase();
// Delegate printing responsibility
printer.print(result);
}
}
Usage:
public class Main {
public static void main(String[] args) {
// Can switch delegate at construction time
DocumentProcessor processor1 = new DocumentProcessor(new ConsolePrinter());
processor1.process("quarterly_report.pdf");
DocumentProcessor processor2 = new DocumentProcessor(new TimestampedPrinter());
processor2.process("annual_audit.pdf");
}
}
3. The Fragile Base Class Pitfall: Inheritance vs Composition
A famous demonstration of inheritance fragility from Joshua Bloch's Effective Java involves tracking the number of elements added to a set.
Fragile Approach (Inheritance)
import java.util.Collection;
import java.util.HashSet;
public class BrokenInstrumentedHashSet<E> extends HashSet<E> {
private int addCount = 0;
@Override
public boolean add(E e) {
addCount++;
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c); // BUG: HashSet.addAll() internally calls add()!
}
public int getAddCount() {
return addCount;
}
}
If you call addAll(List.of("A", "B", "C")):
BrokenInstrumentedHashSet.addAll()adds 3 toaddCount.- It calls
super.addAll(). - Java's
HashSet.addAll()iterates and callsthis.add()for each item. - Because
this.add()is overridden in the subclass,addCountis incremented 3 more times! - Result:
addCountreports6instead of3.
Robust Approach (Composition + Forwarding Decorator)
Instead of extending HashSet, wrap a Set instance and delegate all standard operations:
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
// Forwarding wrapper class
public class ForwardingSet<E> implements Set<E> {
private final Set<E> delegate;
public ForwardingSet(Set<E> delegate) {
this.delegate = delegate;
}
@Override public int size() { return delegate.size(); }
@Override public boolean isEmpty() { return delegate.isEmpty(); }
@Override public boolean contains(Object o) { return delegate.contains(o); }
@Override public Iterator<E> iterator() { return delegate.iterator(); }
@Override public Object[] toArray() { return delegate.toArray(); }
@Override public <T> T[] toArray(T[] a) { return delegate.toArray(a); }
@Override public boolean add(E e) { return delegate.add(e); }
@Override public boolean remove(Object o) { return delegate.remove(o); }
@Override public boolean containsAll(Collection<?> c) { return delegate.containsAll(c); }
@Override public boolean addAll(Collection<? extends E> c) { return delegate.addAll(c); }
@Override public boolean retainAll(Collection<?> c) { return delegate.retainAll(c); }
@Override public boolean removeAll(Collection<?> c) { return delegate.removeAll(c); }
@Override public void clear() { delegate.clear(); }
}
Now extend the forwarding wrapper to safely instrument count:
import java.util.Collection;
import java.util.Set;
public class InstrumentedSet<E> extends ForwardingSet<E> {
private int addCount = 0;
public InstrumentedSet(Set<E> delegate) {
super(delegate);
}
@Override
public boolean add(E e) {
addCount++;
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c); // Delegates safely without internal self-use interference
}
public int getAddCount() {
return addCount;
}
}
Usage with any Set implementation (e.g., HashSet, TreeSet, LinkedHashSet):
Set<String> set = new InstrumentedSet<>(new HashSet<>());
set.addAll(java.util.List.of("A", "B", "C"));
System.out.println("Add count: " + ((InstrumentedSet<String>) set).getAddCount()); // Exactly 3
4. Comparison: Inheritance vs Composition
| Characteristic | Inheritance (extends) |
Composition & Delegation (has-a) |
|---|---|---|
| Relationship | "Is-a" (Cat is an Animal) | "Has-a" (Car has an Engine) |
| Coupling | Tight (compile-time dependency on parent) | Loose (interacts through explicit interfaces) |
| Runtime Swapping | Not possible | Trivial (reassign or inject delegate) |
| Encapsulation | Breaches superclass encapsulation | Preserves object encapsulation |
| Extensibility | Limited by single inheritance in Java | Can compose multiple delegates |
| Testing | Difficult to isolate superclass behaviors | Easy to inject mocks/test doubles |
5. Guidelines: When to Use Each
- Use Inheritance only when:
- There is a genuine, unconditional "is-a" relationship (the subtype truly passes the Liskov Substitution Principle).
- You intend to expose the entire public API of the superclass.
- The superclass is explicitly designed and documented for extension (e.g.,
abstractclasses template methods).
- Use Composition and Delegation when:
- You only need a subset of the functionality of another class.
- You want to reuse behavior across unrelated class hierarchies.
- You need to alter or enrich behavior at runtime (e.g., Decorator or Strategy patterns).