LOW-LEVEL DESIGN · OBJECT-ORIENTED PROGRAMMING · FOUNDATIONS · 7 OF 48

Composition Over Inheritance in Java: Has-a, Delegation, Examples

Why designers prefer composition to inheritance, shown with delivery riders: the subclass explosion when two kinds of variation multiply, has-a relationships and delegation, swapping behaviour at runtime, easier testing with fakes, escaping the fragile base class, the patterns built on it, and when inheritance is still the right call, with Java 17 code.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 16

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 175 lines, with a small main() demo. Save it as CompositionDemo.java, then run javac CompositionDemo.java && java CompositionDemo.

import java.util.ArrayList;
import java.util.List;

/**
 * Composition over inheritance with delivery riders.
 * Part 1: inheritance - one subclass per (vehicle x payment) combination, code copied around.
 * Part 2: composition - a rider HAS a Vehicle and a PaymentCollector and delegates to them,
 *         so parts can be swapped at runtime and faked in tests.
 */
public class CompositionDemo {

    public static void main(String[] args) {
        // ---------- Part 1: the problem ----------
        OldRider old = new BikeCashRider("Arun");
        System.out.println("Inheritance: " + old.getClass().getSimpleName()
                + " eta for 3 km = " + old.etaMinutes(3) + " min (and it can never change class)");

        // ---------- Part 2: the clean version ----------
        DeliveryRider arun = new DeliveryRider("Arun", new Bicycle(), new CashOnDelivery());
        Dispatcher dispatcher = new Dispatcher();

        System.out.println("ETA for 3 km: " + arun.etaMinutes(3) + " min");
        System.out.println(arun.deliver(new Order(51, 240)));

        // The bicycle breaks: swap ONE part, keep the same rider object and its state.
        dispatcher.replaceVehicle(arun, new EScooter());
        System.out.println("After swap, ETA for 3 km: " + arun.etaMinutes(3) + " min");
        System.out.println(arun.deliver(new Order(52, 180)));
        System.out.println(arun.name() + " delivered orders " + arun.delivered());

        // A prepaid rider: same class, different part. No new subclass needed.
        DeliveryRider meera = new DeliveryRider("Meera", new EScooter(), new Prepaid());
        System.out.println(meera.deliver(new Order(53, 410)));

        // Testing: lambdas are enough, because the parts are small interfaces.
        DeliveryRider test = new DeliveryRider("test", km -> 0, o -> "ok");
        System.out.println("Fake parts -> eta " + test.etaMinutes(5) + ", " + test.deliver(new Order(1, 1)));
    }
}

// ---------- Part 1: the problem (only 2 of the 6 combinations shown) ----------

abstract class OldRider {
    final String name;

    OldRider(String name) {
        this.name = name;
    }

    abstract int etaMinutes(int km);

    abstract String collect(Order o);
}

class BikeCashRider extends OldRider {
    BikeCashRider(String name) {
        super(name);
    }

    @Override
    int etaMinutes(int km) {
        return km * 4;                         // bicycle code...
    }

    @Override
    String collect(Order o) {
        return "cash " + o.amount();           // cash code...
    }
}

class BikePrepaidRider extends OldRider {
    BikePrepaidRider(String name) {
        super(name);
    }

    @Override
    int etaMinutes(int km) {
        return km * 4;                         // ...the same bicycle code, copied
    }

    @Override
    String collect(Order o) {
        return "nothing to collect";
    }
}
// ScooterCashRider, ScooterPrepaidRider, MotorbikeCashRider, MotorbikePrepaidRider ...

// ---------- Part 2: composition ----------

record Order(int id, long amount) {
}

/** One kind of variation: how the rider travels. */
@FunctionalInterface
interface Vehicle {
    int minutesFor(int km);
}

/** Another, independent kind of variation: how payment is handled. */
@FunctionalInterface
interface PaymentCollector {
    String collect(Order order);
}

class Bicycle implements Vehicle {
    @Override
    public int minutesFor(int km) {
        return km * 4;
    }
}

class EScooter implements Vehicle {
    @Override
    public int minutesFor(int km) {
        return km * 2;
    }
}

class CashOnDelivery implements PaymentCollector {
    @Override
    public String collect(Order order) {
        return "collected " + order.amount() + " in cash";
    }
}

class Prepaid implements PaymentCollector {
    @Override
    public String collect(Order order) {
        return "already paid online, nothing to collect";
    }
}

/** HAS a vehicle and a collector, and delegates to them. Keeps its own state. */
class DeliveryRider {
    private final String name;
    private Vehicle vehicle;                       // not final: can be swapped at runtime
    private final PaymentCollector collector;
    private final List<Integer> delivered = new ArrayList<>();

    DeliveryRider(String name, Vehicle vehicle, PaymentCollector collector) {
        this.name = name;
        this.vehicle = vehicle;
        this.collector = collector;
    }

    int etaMinutes(int km) {
        return vehicle.minutesFor(km);             // delegation
    }

    String deliver(Order order) {
        delivered.add(order.id());
        return name + " delivered order " + order.id() + ": " + collector.collect(order);
    }

    void switchVehicle(Vehicle replacement) {
        if (replacement == null) {
            throw new IllegalArgumentException("a rider needs a vehicle");
        }
        this.vehicle = replacement;
    }

    String name() {
        return name;
    }

    List<Integer> delivered() {
        return List.copyOf(delivered);
    }
}

class Dispatcher {
    void replaceVehicle(DeliveryRider rider, Vehicle replacement) {
        rider.switchVehicle(replacement);
    }
}

Notes

The problem

A delivery rider varies in two ways. How they travel: bicycle, electric scooter or motorbike. And how payment is handled: cash at the door or prepaid. With inheritance, each combination becomes a subclass, so three times two gives six classes, like bike cash rider. Add cars and you need two more. Add U P I at the door and you need four more. The travel code is copied across every payment variant.

Subclass explosion
  • vehicle: bicycle, e-scooter,
  • motorbike
  • payment: cash, prepaid
  • 3 x 2 = 6 subclasses:
  • BikeCashRider
  • BikePrepaidRider
  • ScooterCashRider ...
  • add "car": 2 more classes
  • add "UPI at door": 4 more

Stuck at birth

There is a second limit. A Java object can never change its class. Arun starts the shift as a bike cash rider. His bicycle breaks, and he switches to an electric scooter. The object cannot become a scooter cash rider. You would have to create a new rider object and copy over his orders in hand and his rating, and hope nothing else still points to the old one.

Another limit
Rider r = new BikeCashRider("Arun");

// bike breaks down mid-shift
// Arun takes an e-scooter

// r cannot become a
// ScooterCashRider object.
// create a new rider? lose state
// like orders in hand and rating

The idea

Composition means building an object from parts that it holds, and letting each part do its own job. Inheritance says is a. Composition says has a. A delivery rider has a vehicle and has a way to collect payment. Each kind of variation becomes its own small interface, and the rider just holds one of each. The two kinds of variation stop multiplying and start adding.

In one sentence
  • composition: build an object
  • from parts it holds, and let
  • each part do its own job
  • inheritance: is-a
  • composition: has-a
  • a rider HAS a vehicle
  • a rider HAS a way to collect

The structure

Here is the structure. Vehicle is an interface with one method, minutes for a distance. Bicycle and electric scooter implement it. Payment collector is another interface, with cash on delivery and prepaid behind it. With inheritance, the counts multiplied. With composition, they add: three vehicles plus two collectors. Adding a car is one class, and adding U P I at the door is one class.

Count the classes
  • inheritance:
  • vehicles x payments
  • 3 x 2 = 6, growing fast
  • composition:
  • vehicles + payments
  • 3 + 2 = 5, growing slowly
  • add a car: one class
  • add UPI at door: one class

Delegation

The rider holds its parts in private fields, passed in through the constructor. When asked for an arrival time, it simply asks its vehicle. When delivering an order, it asks its collector to handle payment. Passing a job to another object like this is called delegation. The rider keeps its own state, like its name and the orders in hand, and does not need to know how any part works inside.

class DeliveryRider
private Vehicle vehicle;
private final PaymentCollector collector;

int etaMinutes(int km) {
  return vehicle.minutesFor(km);
}
String deliver(Order o) {
  return collector.collect(o);
}

Run-through

Follow the demo. The dispatcher asks Arun for an arrival time for three kilometres. Arun asks his bicycle, which says twelve minutes at four minutes per kilometre. Then the dispatcher asks him to deliver order fifty one. Arun hands that to his cash on delivery collector, which records two hundred and forty rupees taken at the door. Each object answered only for its own job.

Swap at runtime

Now the bicycle breaks. The dispatcher calls switch vehicle and hands Arun an electric scooter. It is the same rider object, with the same orders in hand and the same rating. Only one part changed. The next arrival time comes from the scooter: six minutes for three kilometres. With inheritance this needed a new object. With composition it is one field assignment.

Testing

Testing becomes easy. Because Vehicle and payment collector are small interfaces with one method each, a test can pass in lambdas: a vehicle that always takes zero minutes and a collector that always says okay. Now you can test the rider's own logic, like how it tracks orders, with nothing else involved. With six subclasses, you would have had to test each combination separately.

A test in three lines
Vehicle instant = km -> 0;
PaymentCollector noop = o -> "ok";
var r = new DeliveryRider("t",
    instant, noop);

assert r.etaMinutes(5) == 0;

Vehicle is a functional interface,
so a lambda is enough

No fragile base

Composition also escapes the fragile base class problem from lesson four. A subclass depends on its parent's insides, such as which methods call which. The rider depends only on the public methods of Vehicle and payment collector. The scooter team can change how they calculate time in any way they like, and as long as the contract holds, the rider is never affected.

Safer coupling
  • inheritance couples you to
  • the parent's insides:
  • call order, protected parts
  • composition couples you
  • only to public methods
  • a part can change how it
  • works inside and the rider
  • never notices

Side by side

Side by side. Inheritance models is a, is fixed when the code is compiled, couples to the parent's insides, and makes combinations multiply. Composition models has a, can be changed at runtime, couples only to public methods, and makes combinations add. The price of composition is a little more code: you write forwarding methods instead of getting inherited ones for free.

Inheritance vs composition
  • inherit compose
  • relation is-a has-a
  • fixed when compile runtime
  • can swap no yes
  • coupling insides public
  • combinations multiply add
  • code to write less a bit
  • more

When to inherit

The advice says prefer, not always. Inheritance is fine for a strict is a relationship that will not change, when the base class was designed for extension with clear hooks, and when there is only one kind of variation. Some frameworks also expect you to extend their classes. The danger signs are two or more kinds of variation, and a need to change behaviour while the program is running.

Inheritance is fine when
  • • the is-a is strict and
  • will not change
  • • the base was designed for
  • extension (template steps)
  • • one kind of variation,
  • not two or more
  • • framework asks for it
  • (extend a test base class)

In the JDK

The Java library uses composition everywhere. A Thread is given a Runnable to run instead of being subclassed. A buffered reader wraps another reader and adds buffering on top. Collections dot synchronized list wraps any list and puts a lock around each call. A tree map takes a Comparator that decides its ordering. In each case behaviour is plugged in, not inherited.

Composition in Java
  • new Thread(runnable)
  • thread has a task
  • BufferedReader(Reader)
  • wraps another reader
  • Collections.synchronizedList
  • wraps a list, adds a lock
  • TreeMap(Comparator)
  • has an ordering

Patterns built on it

Many design patterns are composition with a name. The vehicle and payment collector are Strategy: an algorithm held in a field and swapped when needed. Decorator wraps an object to add behaviour, like the buffered reader. State swaps the held object as the state changes. Adapter wraps an object to make it fit another interface. You will meet each of these in the patterns unit.

Named patterns
  • Strategy: swap an algorithm
  • (Vehicle, PaymentCollector)
  • Decorator: wrap to add
  • behaviour (BufferedReader)
  • State: swap behaviour as
  • the state changes
  • Adapter: wrap to translate
  • one interface into another

In interviews

In design rounds, reach for composition when you see variations multiplying or behaviour that changes at runtime. A parking lot holds a pricing policy. An elevator holds a scheduling strategy. A vending machine holds its current state. A logger holds sinks and formatters. The classic mistake is a tall tree like vehicle, car, electric car, electric S U V, growing one level for every new feature.

Where it shows up
  • parking lot: PricingPolicy
  • held by the lot
  • elevator: scheduling strategy
  • vending machine: current state
  • logger: sinks and formatters
  • mistake: Vehicle -> Car ->
  • ElectricCar -> ElectricSUV
  • for every new feature

Interview questions

What does "favour composition over inheritance" mean?

Prefer building classes that hold other objects and delegate work to them, rather than extending a class to reuse its code. Composition keeps classes loosely coupled, lets behaviour change at runtime and avoids deep, fragile hierarchies.

What is the difference between composition and inheritance?

Inheritance creates an is-a relationship fixed at compile time; the subclass reuses and depends on the parent's implementation. Composition creates a has-a relationship; the object holds references to parts and calls their public methods, and those parts can be replaced at runtime.

What is delegation?

Delegation is when an object handles a request by forwarding it to another object it holds, such as a rider asking its vehicle for travel time. It is the mechanism that makes composition work.

What is the subclass explosion problem?

When a class varies along two or more independent dimensions, inheritance needs a subclass for every combination, so the number of classes multiplies. Composition puts each dimension behind its own interface, so the number of classes only adds up.

When is inheritance still the better choice?

When there is a strict, stable is-a relationship, a single dimension of variation, and a base class designed for extension, such as an abstract class with a fixed algorithm and hook methods. Frameworks that require subclassing are another case.

How does composition make code easier to test?

The parts sit behind interfaces and are passed in, often through the constructor, so a test can supply simple fakes or lambdas. The class under test can then be checked in isolation, without real dependencies.

Which design patterns are based on composition?

Strategy holds a swappable algorithm, Decorator wraps an object to add behaviour, State replaces the held object as state changes, Adapter wraps an object to match another interface, and Composite builds trees of objects. All of them rely on holding references instead of extending classes.

What is the difference between composition and aggregation?

Both are has-a relationships. In composition the part's life is owned by the whole and usually ends with it, like rooms in a house. In aggregation the part can exist independently and may be shared, like a rider and the vehicle assigned for a shift.