Skip to lesson

Composition vs Inheritance

A common design round question is "inheritance or composition?", often followed by "refactor this hierarchy". The interviewer checks whether you know why "favour composition" is advice, and when inheritance is still correct.

IS-A vs HAS-A; association, aggregation, composition

HAS-A means a class holds another object as a field and delegates work to it, like a Car that has an Engine. It comes in three strengths: association, aggregation and composition.

IS-A is inheritance (SavingsAccount extends Account). HAS-A is a field. The code shows one example of each of its three strengths.

Class diagram. SmartPhone points to Phone with an arrow labelled "is a" (extends). SmartPhone is joined to Camera by a line with a diamond at the SmartPhone end, labelled "has a" (a private Camera field). One parent, any number of parts.

Example 1 · Association, aggregation and composition in code

Relationships.javaJava
import java.util.ArrayList;import java.util.List;
class Course {    final String code;    Course(String code) { this.code = code; }}
class Student {    final String name;    Student(String name) { this.name = name; }    String enrol(Course c) { return name + " enrolled in " + c.code; }}
class Professor {    final String name;    Professor(String name) { this.name = name; }}
class Department {                                // aggregation: professors passed in, can be shared    private final List<Professor> staff = new ArrayList<>();    void hire(Professor p) { staff.add(p); }    int size() { return staff.size(); }}
class Order {                                     // composition: order creates and owns its lines    private final List<String> lines = new ArrayList<>();    void addLine(String item, int qty) { lines.add(qty + " x " + item); }    List<String> lines() { return List.copyOf(lines); }}
public class Relationships {    public static void main(String[] args) {        System.out.println(new Student("Asha").enrol(new Course("CS101")));
        Professor rao = new Professor("Dr Rao");        Department cse = new Department();        Department ai = new Department();        cse.hire(rao);        ai.hire(rao);                             // the same professor, shared        System.out.println(rao.name + " works in " + (cse.size() + ai.size()) + " departments");
        Order order = new Order();        order.addLine("Notebook", 3);        order.addLine("Pen", 5);        System.out.println(order.lines());    }}
Output
Asha enrolled in CS101
Dr Rao works in 2 departments
[3 x Notebook, 5 x Pen]

What this code does

  • Student only uses a Course in a method: association. Department receives existing professors, and one professor is shared by two departments: aggregation.
  • Order creates its line objects itself and hands out only a copy, so the lines live and die with the order: composition.

Association: one object uses another, a Student enrolled in a Course. Aggregation: a whole holds parts that can live on their own and be shared, a Department and its Professors. Composition: the whole owns parts that do not exist without it, an Order and its OrderLines.

Must know:

  • IS-A → extends/implements; HAS-A → a field
  • association: uses; aggregation: shared parts, independent life; composition: owned parts, same life

Why favour composition: the fragile base class

The fragile base class problem is a subclass breaking because of how its parent is implemented inside, even though the subclass's own code did not change.

The classic case is a counting set that extends HashSet and overrides add and addAll. The code compares it with a version that holds the set instead.

Example 2 · Fragile base class: counting with inheritance vs composition

FragileBase.javaJava
import java.util.Collection;import java.util.HashSet;import java.util.List;import java.util.Set;
class InheritedCountingSet extends HashSet<String> {    int added = 0;
    @Override    public boolean add(String s) {        added++;        return super.add(s);    }
    @Override    public boolean addAll(Collection<? extends String> c) {        added += c.size();        return super.addAll(c);                   // HashSet's addAll calls add() again    }}
class ComposedCountingSet {    private final Set<String> inner = new HashSet<>();    int added = 0;
    boolean add(String s) {        added++;        return inner.add(s);    }
    boolean addAll(Collection<? extends String> c) {        added += c.size();        return inner.addAll(c);                   // inner calls stay inside inner    }
    int size() {        return inner.size();    }}
public class FragileBase {    public static void main(String[] args) {        List<String> names = List.of("Asha", "Ravi", "Meera");
        InheritedCountingSet a = new InheritedCountingSet();        a.addAll(names);        System.out.println("Inheritance: added = " + a.added + ", size = " + a.size());
        ComposedCountingSet b = new ComposedCountingSet();        b.addAll(names);        System.out.println("Composition: added = " + b.added + ", size = " + b.size());    }}
Output
Inheritance: added = 6, size = 3
Composition: added = 3, size = 3

What this code does

  • The inherited version reports 6 for 3 names: addAll adds 3, then HashSet.addAll (inherited from AbstractCollection) calls the overridden add three more times.
  • The composed version counts 3, because calls inside the private inner set never reach the wrapper's add. Its correctness no longer depends on how HashSet is written.

HashSet.addAll happens to call add for each element, so every element is counted twice. The subclass did nothing wrong in its own code; it depended on a detail it could not see.

A composition version that holds a private Set and forwards calls is immune: the inner set's internal calls never come back into the wrapper.

Predict the output

Count the additions

Predict the exact output, then read why.

Round 1 of 2

The same counting trick, this time extending ArrayList.

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
class CountingList extends ArrayList<String> {
int adds = 0;
@Override
public boolean add(String s) {
adds++;
return super.add(s);
}
@Override
public boolean addAll(Collection<? extends String> c) {
adds += c.size();
return super.addAll(c);
}
}
public class Round1 {
public static void main(String[] args) {
CountingList list = new CountingList();
list.addAll(List.of("Asha", "Ravi", "Meera"));
System.out.println(list.adds + " " + list.size());
}
}

Refactor an inheritance hierarchy to composition

Class explosion is a hierarchy that needs a subclass for every combination of choices, such as PetrolManualCar and ElectricAutomaticCar. Composition replaces them with one field for each choice.

Engine type and gearbox type each vary, so inheritance needs a subclass for every pair. The refactor turns each varying part into an interface held as a field.

Example 3 · Refactoring car subclasses into composition

CarComposition.javaJava
interface Engine {    String start();}
interface Gearbox {    String shift();}
class PetrolEngine implements Engine {    public String start() { return "petrol engine roars"; }}
class ElectricEngine implements Engine {    public String start() { return "electric motor hums"; }}
class ManualGearbox implements Gearbox {    public String shift() { return "driver shifts gears"; }}
class AutomaticGearbox implements Gearbox {    public String shift() { return "gears shift automatically"; }}
class Car {    private Engine engine;                        // HAS-A, any implementation    private final Gearbox gearbox;
    Car(Engine engine, Gearbox gearbox) {        this.engine = engine;        this.gearbox = gearbox;    }
    String drive() {        return engine.start() + ", " + gearbox.shift();    }
    void replaceEngine(Engine newEngine) {        // change behaviour at run time        this.engine = newEngine;    }}
public class CarComposition {    public static void main(String[] args) {        Car city = new Car(new PetrolEngine(), new ManualGearbox());        Car taxi = new Car(new ElectricEngine(), new AutomaticGearbox());        System.out.println(city.drive());        System.out.println(taxi.drive());
        city.replaceEngine(new ElectricEngine());        System.out.println(city.drive());    }}
Output
petrol engine roars, driver shifts gears
electric motor hums, gears shift automatically
electric motor hums, driver shifts gears

What this code does

  • Instead of four subclasses (one per engine and gearbox pair), there are two small interfaces and one Car. A third engine type adds one class, not three.
  • replaceEngine changes a car's behaviour while the program runs; with PetrolManualCar as a subclass that would be impossible.

Example 4 · A stack that extends a list vs a stack that has one

StackDesign.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;
class BadStack extends ArrayList<Integer> {    void push(int x) { add(x); }    int pop() { return remove(size() - 1); }}
class GoodStack {                                // HAS-A deque: only stack operations exposed    private final Deque<Integer> items = new ArrayDeque<>();    void push(int x) { items.push(x); }    int pop() { return items.pop(); }    boolean isEmpty() { return items.isEmpty(); }}
public class StackDesign {    public static void main(String[] args) {        BadStack bad = new BadStack();        bad.push(1);        bad.push(2);        bad.add(0, 99);                          // allowed: breaks stack order        System.out.println("BadStack pops " + bad.pop() + " then " + bad.pop() + " then " + bad.pop());
        GoodStack good = new GoodStack();        good.push(1);        good.push(2);        // good.add(0, 99);                      // does not compile: no such method        System.out.println("GoodStack pops " + good.pop() + " then " + good.pop());    }}
Output
BadStack pops 2 then 1 then 99
GoodStack pops 2 then 1

What this code does

  • BadStack inherits add(int, E), so any caller can slip 99 under the stack; the JDK's own Stack extends Vector has the same flaw.
  • GoodStack holds a Deque and exposes only push, pop and isEmpty, so stack order cannot be broken from outside.

Now any combination is two objects passed to one Car, and an engine can even be replaced at run time. The same move fixes classes that inherit methods they must not expose, like Stack extends Vector.

Order of execution

Refactor to composition

Put the refactoring steps in the order you would explain them.

Follow-up questions: when inheritance is right

Liskov substitution means a subclass object must work anywhere its parent is expected, with every inherited method still making sense. If it does not, inheritance is the wrong tool.

Inheritance is still right for a genuine IS-A, a class designed for extension, or a framework base class. The code shows a safe subclass and a custom exception.

Example 5 · Where inheritance is right

GoodInheritance.javaJava
class Account {    protected int balance;
    Account(int balance) {        this.balance = balance;    }
    void deposit(int amount) {        balance += amount;    }
    int getBalance() {        return balance;    }}
class SavingsAccount extends Account {            // a true IS-A: usable anywhere an Account is    private final double rate;
    SavingsAccount(int balance, double rate) {        super(balance);        this.rate = rate;    }
    void addInterest() {        deposit((int) (balance * rate / 100));    }}
class InsufficientFundsException extends RuntimeException {   // framework-style extension    InsufficientFundsException(int shortBy) {        super("Short by Rs " + shortBy);    }}
public class GoodInheritance {    static void salaryCredit(Account a) {        a.deposit(30000);    }
    public static void main(String[] args) {        SavingsAccount s = new SavingsAccount(10000, 4.0);        salaryCredit(s);                          // works: substitutable        s.addInterest();        System.out.println("Balance: Rs " + s.getBalance());
        try {            throw new InsufficientFundsException(500);        } catch (RuntimeException e) {            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());        }    }}
Output
Balance: Rs 41600
InsufficientFundsException: Short by Rs 500

What this code does

  • Every Account method makes sense on a SavingsAccount, and salaryCredit works unchanged with it: a genuine IS-A that passes the substitution test.
  • Custom exceptions extending RuntimeException are inheritance by design: Java's exception handling is built around the hierarchy.

A custom exception extends RuntimeException, and a JUnit or servlet base class is meant to be extended.

A quick test to say aloud: "Does every inherited public method still make sense on the child?" If you need to override methods just to block them or throw UnsupportedOperationException, use composition instead.

Find the bug

Is inheritance the wrong tool?

Tap the line that shows the design smell.

A read-only list is built by extending ArrayList.

Round 1 of 2

Next step

Check your understanding

12 quick questions