Stop 05 · Inheritance, Polymorphism & InterfacesTopics · 6/9

Composition over Inheritance

Part of the Java Roadmap

In short

Deep inheritance trees look clever on day one and become painful by month three. Most experienced Java developers reach for composition first: build objects out of other objects.

Composition means building a class from other objects it holds (has-a) instead of extending a parent (is-a). It keeps classes loosely coupled and avoids fragile, deep inheritance trees.

The jaadu swaps one small steel bowl out of a round thali for another, while the rest of the bowls on the plate stay in place.

Think of it like this

A thali, not a family tree

A thali is made of separate bowls: dal, rice, sabzi, roti. Want rajma instead of dal? Swap one bowl. Nobody redesigns the whole plate. A class built with composition holds its parts as fields (a car has an engine), so you can swap one part without rewriting the class or its parents.

Watch it happen

Car delegates to whatever engine it holds

Driver
Car
Engine

drive()

1/3The driver asks the car to drive. The driver never talks to the engine.

The big ideas

What you need to know

has-a instead of is-a

A Car has an Engine. It is not an Engine. If the is-a sentence sounds odd, use a field.

Swap parts freely

Pass any Engine implementation into the constructor. With inheritance you'd need a new subclass for each combination.

Less fragile

A change inside a parent class can silently break all children. A composed object only depends on the part's public methods.

A famous mistake

Java's own Stack extends Vector, so a Stack exposes methods like insertElementAt that break stack rules. Composition would have hidden them.

See it in code

Walk through the code

java
1interface Engine {2    String start();3}4 5class PetrolEngine implements Engine {6    @Override7    public String start() {8        return "Petrol engine roars";9    }10}11 12class ElectricMotor implements Engine {13    @Override14    public String start() {15        return "Electric motor hums quietly";16    }17}18 19class Car {20    private final String model;21    private final Engine engine;22 23    Car(String model, Engine engine) {24        this.model = model;25        this.engine = engine;26    }27 28    void drive() {29        System.out.println(model + ": " + engine.start());30    }31}32 33public class Garage {34    public static void main(String[] args) {35        new Car("Nexon", new PetrolEngine()).drive();36        new Car("Nexon EV", new ElectricMotor()).drive();37    }38}

1/4A small interface for the part we want to swap.

Same Car class, two different engines, no subclass needed.

Save yourself the pain

Common mistakes

Oops

Creating PetrolCar, ElectricCar, PetrolAutomaticCar, ElectricAutomaticCar and so on.

Do this instead

Every new combination multiplies subclasses. Hold an Engine and a Gearbox as fields and combine them freely.

Oops

Extending ArrayList to make a ShoppingCart.

Do this instead

A cart has a list of items. Keep a private List<Item> field and expose only the methods a cart needs.

Oops

Thinking inheritance is now banned.

Do this instead

Inheritance is fine for a true, stable is-a relationship. Composition is simply the safer default.

Your mission

Refactor a subclass explosion

~30 min

Quick check

Which relationship is best modelled with composition?

Go deeper

  1. 1Refactor a class that extends another just to reuse code so it holds that object instead.
  2. 2Model a Car that has an Engine rather than a Car that is an Engine.
  3. 3Read why Effective Java recommends favouring composition over inheritance.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge