Lesson · Composition & Delegation
Composition and delegation: reuse without the promise
15 min readComposition & Delegation
Hold the other object instead of becoming it: a private field, a few forwarding methods, and the wrapper owns its behaviour. HAS-A gives control that IS-A gives away.
The counter that finally counts once
The counting set from the inheritance design lesson double-counted because the parent called its own methods. Hold the set instead, and each call has exactly one door:
class CountingSet<E> { private final Set<E> inner = new HashSet<>(); // HAS-A: holds a set private int count = 0; boolean add(E e) { count++; // counted here, once return inner.add(e); // delegated to the real set } }
Predict: the same addAll of three items that reported 6 before: how many do these two methods count now? Exactly three, because the wrapper's addAll adds three and the inner set's internals never route back through the wrapper. Control came from ownership, not from overriding.
Delegation: forwarding, on purpose
The mechanics are plain: your class holds another object, and chosen calls are forwarded to it:
| Word | Means |
|---|---|
| HAS-A | The relationship: your object owns a helper (a list, a set, a notifier) as a field |
| delegation | Forwarding a call to that helper instead of doing the work yourself |
| forwarding method | The one-line method that delegates: return inner.add(e); |
- Add a private field of the helper (or of its interface).
- Expose only the operations your type promises; everything else simply does not exist on your class.
- Forward each chosen method to the field with one line.
- Add whatever behaviour you wanted (counting, logging, validation) around the forward.
Delegation is a decision per method, not per class. Inheritance decides everything at once; a wrapper hands you a checklist: which calls pass through, and what happens on the way.
Wrappers and decorators: same interface, extra behaviour
The most useful shape is a wrapper that implements the same interface it wraps, so callers cannot tell it is there except for the extra behaviour:
interface Notifier { void send(String msg); } class LoggingNotifier implements Notifier { // same interface: a decorator private final Notifier inner; // holds one LoggingNotifier(Notifier inner) { this.inner = inner; } public void send(String msg) { log(msg); // the added behaviour inner.send(msg); // the delegation } }
- The client still calls
sendon aNotifier; it never learns that a wrapper joined the chain. - The wrapper logs first, then forwards; the real notifier still sends.
- The wrapper is itself a Notifier, so wrappers stack: a logging wrapper around a counting wrapper around the real one.
- You have seen this in the JDK:
Collections.unmodifiableList,Collections.synchronizedListand buffered streams are all decorators.
A decorator is composition made invisible. Same interface in, same interface out, new behaviour in between; callers keep programming against the contract and never chase the chain.
One call, three players · client → wrapper → inner
Current statement
client · calls send("hi")
LoggingNotifier · log(msg) then forward
wrapperinner · EmailNotifier · send(msg)
private fieldOutput
nothing yet
The wrapper implements the same interface it wraps and holds one instance in a private field. From the outside it is a Notifier like any other.
Hand-made injection: pass the part in
If the field is private final and set through the constructor, the wrapper never chooses its parts; the caller does. That one habit delivers three things:
- Swappable parts: the field's type is the interface, so the real notifier, a logging decorator or a test fake all plug in without touching the class.
- Honest dependencies: everything the object needs is visible in the constructor; nothing is created secretly inside.
- Testable seams: a fake is a constructor argument, not a mocking framework adventure. Frameworks automate this pattern; the pattern is just this.
Program to the interface, wire in the constructor. Field types and parameter types say Notifier, never EmailNotifier; construction happens once, at the edge, and the middle of the program stays swappable.
The composition playbook
Reaching for has-a, in order:
- Ask the sentence again: 'has a' or 'wraps a' picks composition; only a true and permanent 'is a' earns inheritance.
- Pick the field's type: the interface when one exists, the concrete class only when nothing else fits.
- Forward the methods your type promises, and only those; a wrapper is allowed to have a smaller API.
- Keep the field
private final, set it in the constructor; no setters, no leaky getters. - When behaviour must be added around an existing implementation, write the same-interface wrapper; that is the decorator, and it composes forever.
A few forwarding lines buy full control. The wrapper decides its surface, its behaviour and its parts, and no parent's future changes can reach it uninvited.
Hold the behaviour; do not become it
Composition stores the helper in a private field and delegation forwards chosen calls to it. Same-interface wrappers (decorators) add behaviour invisibly, constructor injection hands the parts in through an interface type, and every one of these keeps a wrapper's API smaller and safer than an inherited one.
Interview angles
Composition versus inheritance, short version?+
Inheritance says 'is a' and inherits an entire permanent contract; composition says 'has a' and forwards chosen calls to a helper you own and can swap.
Reach for inheritance only on a true, permanent is-a with a parent designed for extension; compose for reuse, for cross-family capabilities, and whenever the parent is outside your control. Wrapping keeps the parent's future changes behind the wall.
class Stack<T> { // has-a list private final List<T> items = new ArrayList<>(); void push(T item) { items.add(item); } // forwarded, on purpose }
Common misconception: That composition means duplicating the helper's API. It means choosing a smaller one; unforwarded methods simply do not exist for callers.
Follow-up: What does the wrapper give up compared with extending?
What exactly is delegation?+
A method that forwards the call to another object: return inner.add(item);. The wrapper owns the interaction, the helper owns the work.
Delegation is decided per method, which is the point: each forwarded call can gain behaviour (counting, logging, validation) on the way through, and the wrapper's class always knows which calls exist.
boolean add(E e) { count++; // added behaviour return inner.add(e); // delegation }
Common misconception: That delegation is just 'calling another object'. The pattern part is ownership: the helper is a private field, not a stranger passed in for one call.
Follow-up: When is delegation the wrong tool?
What is a decorator, and why does the same interface matter?+
A wrapper that implements the interface it wraps, so it can stand in anywhere the original could and add behaviour invisibly: logging, counting, synchronisation, buffering.
Same-interface wrappers stack in any order, and callers never see the chain: Collections.unmodifiableList(Collections.synchronizedList(list)) is decorators all the way down.
interface Notifier { void send(String msg); } class LoggingNotifier implements Notifier { /* logs, then forwards */ }
Common misconception: That wrappers and subclasses are interchangeable. A decorator works for implementations it never met; a subclass is welded to one parent.
Follow-up: What breaks if the wrapper's interface is slightly different?
What is constructor injection, without the framework vocabulary?+
The object receives its parts as constructor arguments into private final fields typed as interfaces; it never creates or looks up its collaborators.
Everything the object depends on is visible in one signature, swappable in tests, and created once at the edge of the program. Dependency-injection frameworks automate the wiring; the pattern itself is one constructor and one habit.
class OrderService { private final Notifier notifier; OrderService(Notifier notifier) { this.notifier = notifier; } }
Common misconception: That injection is a framework feature. It is a constructor shape; frameworks only spare you the new lines.
Follow-up: Where in a program should the real implementations actually be created?
What does composition cost compared with inheritance?+
Forwarding boilerplate, no inherited identity (the wrapper is not the wrapped type), and deliberate decisions about equality and exposure.
The wrapper is its own type: CountingSet is not a Set unless it implements the interface, and even then it must forward enough methods for the promise to hold. The return is control: smaller API, swappable parts, immunity to the wrapped class's evolution.
// A wrapper is not automatically a Set: class CountingSet<E> { ... } // has add, count, size: its own contract class CountingSet2<E> implements Set<E> { ... } // choosing the promise means forwarding it
Common misconception: That forwarding boilerplate means composition is worse. It is the price of ownership, paid once, in a class that stays small because its API is chosen.
Follow-up: When would a wrapper implement the full interface anyway?