On this page

Composition over Inheritance

In 1994 the "Gang of Four" book, Design Patterns, stated two principles in its introduction. One was "program to an interface, not an implementation." The other was "favour object composition over class inheritance." Thirty years on, it's still one of the most useful defaults in object design, and one of the most misunderstood. It doesn't say inheritance is bad. It says inheritance is a strong, permanent coupling that you should choose deliberately, while composition is a looser one you can choose by default.

This page explains why. It starts with what inheritance actually bundles together, then shows the fragile base class problem with real behaviour from the JDK, CPython and JavaScript runtimes, not a contrived example. After that come the alternatives (delegation, strategy by composition, mixins and traits), the cases where inheritance genuinely is the right tool, and how all of this ties to the Liskov Substitution Principle.

Every sample was run with Java 24, Python 3.12 and TypeScript 5.8 (tsc --strict, then tsx). The Java samples use a small check helper rather than assert, so they fail without the -ea flag.

1. What inheritance bundles together

When B extends A, you get two different things in one keyword:

  1. Subtyping. A B can be used anywhere an A is expected. This is a promise to every caller of A.
  2. Implementation reuse. B gets A's fields and method bodies for free, and can override some of them.

The trouble is that you often want only one of the two. You want to reuse a HashSet's storage without promising to be a HashSet. Or you want several classes to be interchangeable without sharing any code. Inheritance gives you both or neither.

Composition separates them:

You wantInheritance givesComposition gives
Substitutabilityextends (with the base's whole contract)implements an interface you choose, with only the methods you mean
Code reuseEvery non-private member of the base, foreverA field holding a collaborator, plus calls to it
Behaviour chosen at runtimeFixed at construction: an object can't change classSwap the collaborator object
Visibility into internalsProtected members and self-calls, so the subclass couples to the base's implementationOnly the collaborator's public API
Number of combinationsOne subclass per combinationOne small class per dimension, combined freely

The last two rows are the crux. A subclass sees, and depends on, how its base class is built. That dependency is invisible in the code and easy to break.

2. The fragile base class problem

A base class is fragile when reasonable changes to it, or reasonable assumptions about it, break subclasses that the base class author never saw. The root cause is self-use: a base method calling another overridable method on this. When you override one, you change the behaviour of the other, and whether that happens depends on implementation details that the base class never promised.

Joshua Bloch's Effective Java (Item 18, "Favor composition over inheritance") made this famous with an instrumented HashSet. The three runtimes below each show a different flavour of the same problem, and all three are real behaviour of the standard library, not something set up to fail:

  • Java: HashSet.addAll is inherited from AbstractCollection, which calls add for each element. Override both to count, and every bulk add is counted twice.
  • Python: the built-in dict does the opposite. Its update, setdefault and constructor don't call __setitem__, so an override of __setitem__ is silently bypassed. The standard library ships collections.UserDict precisely so subclasses can rely on every write going through __setitem__.
  • JavaScript: the Set constructor calls this.add for each initial element. It runs before the subclass's field initialisers, so a counter field is reset to 0 after the base class has already called the override.
import java.util.*;

// ---------- before: inherit from HashSet to count insert attempts ----------
class InstrumentedSet<E> extends HashSet<E> {
    private int attempts = 0;

    @Override public boolean add(E e) { attempts++; return super.add(e); }

    @Override public boolean addAll(Collection<? extends E> items) {
        attempts += items.size();
        return super.addAll(items);   // AbstractCollection.addAll calls add() for each item
    }

    int attempts() { return attempts; }
}

// ---------- after: wrap a Set and forward to it ----------
final class CountingSet<E> {
    private final Set<E> inner;
    private int attempts = 0;

    CountingSet(Set<E> inner) { this.inner = inner; }

    boolean add(E e) { attempts++; return inner.add(e); }
    boolean addAll(Collection<? extends E> items) { attempts += items.size(); return inner.addAll(items); }
    boolean contains(Object o) { return inner.contains(o); }
    int size() { return inner.size(); }
    int attempts() { return attempts; }
}

class FragileBaseDemo {
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) {
        InstrumentedSet<String> broken = new InstrumentedSet<>();
        broken.addAll(List.of("a", "b", "c"));
        check(broken.attempts() == 6, "before: three items counted as six");

        CountingSet<String> counted = new CountingSet<>(new HashSet<>());
        counted.addAll(List.of("a", "b", "c"));
        check(counted.attempts() == 3, "after: counted once");

        CountingSet<String> sorted = new CountingSet<>(new TreeSet<>());   // works with any Set
        sorted.add("x"); sorted.addAll(List.of("y", "x"));
        check(sorted.attempts() == 3 && sorted.size() == 2, "after: any Set implementation");
        System.out.println("inherited count " + broken.attempts() + ", composed count " + counted.attempts());
    }
}
# ---------- before: inherit from dict to count writes ----------
class CountingDict(dict):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.writes = 0

    def __setitem__(self, key, value) -> None:
        self.writes += 1
        super().__setitem__(key, value)


broken = CountingDict()
broken["a"] = 1
broken.update(b=2, c=3)        # dict.update does not call __setitem__
broken.setdefault("d", 4)      # neither does setdefault
assert len(broken) == 4 and broken.writes == 1   # four writes, one counted


# ---------- after: wrap a dict and route every write through one method ----------
class WriteCounter:
    def __init__(self) -> None:
        self._data: dict[str, int] = {}
        self.writes = 0

    def set(self, key: str, value: int) -> None:
        self.writes += 1
        self._data[key] = value

    def update(self, **items: int) -> None:
        for key, value in items.items():
            self.set(key, value)

    def get(self, key: str) -> int | None:
        return self._data.get(key)

    def __len__(self) -> int:
        return len(self._data)


counted = WriteCounter()
counted.set("a", 1)
counted.update(b=2, c=3)
assert len(counted) == 3 and counted.writes == 3
print(f"inherited count {broken.writes} of 4, composed count {counted.writes} of 3")
function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(what);
}

// ---------- before: inherit from Set to count adds ----------
class InstrumentedSet<T> extends Set<T> {
  added = 0; // initialised AFTER super() returns
  override add(value: T): this {
    this.added++; // during super(initial), this.added is still undefined
    return super.add(value);
  }
}

const broken = new InstrumentedSet(["a", "b", "c"]); // Set's constructor calls this.add three times
broken.add("d");
check(broken.size === 4 && broken.added === 1, "before: four adds, one counted");

// ---------- after: wrap a Set and forward to it ----------
class CountingSet<T> {
  private readonly inner = new Set<T>();
  private added = 0;
  constructor(initial: Iterable<T> = []) {
    for (const v of initial) this.add(v);
  }
  add(value: T): this {
    this.added++;
    this.inner.add(value);
    return this;
  }
  has(value: T): boolean { return this.inner.has(value); }
  get size(): number { return this.inner.size; }
  get attempts(): number { return this.added; }
}

const counted = new CountingSet(["a", "b", "c"]);
counted.add("d");
check(counted.size === 4 && counted.attempts === 4, "after: every add counted");
console.log(`inherited count ${broken.added}, composed count ${counted.attempts}`);

Look at what went wrong in each case. Nobody wrote buggy code. The Java subclass author made a reasonable assumption ("addAll doesn't call add") that happened to be false. The Python author made the opposite assumption ("every write goes through __setitem__") and was also wrong. The JavaScript author didn't think about construction order at all. In each case the subclass's correctness depends on an implementation detail of the base class that its documentation doesn't promise and that could change in a future release.

The composed versions don't have this problem because the wrapper only uses the inner object's public contract. When the wrapper's addAll calls inner.addAll, any internal calls the inner set makes go to its own add, not the wrapper's. The wrapper also works with any Set, which the subclass couldn't.

2.1 The same problem in your own code

Standard libraries at least document some self-use. Your own base classes usually don't. Here's how fragility appears in application code:

  1. Someone writes Account with withdraw and transfer, where transfer calls withdraw.
  2. Someone else writes AuditedAccount extends Account, overriding withdraw to log. Transfers are now logged too, by accident. They write a test that relies on it.
  3. A third person "optimises" Account.transfer to update the balance directly. Every audited transfer silently stops being logged.

Step 3 is a reasonable refactor of Account. Nothing in Account says "subclasses depend on transfer calling withdraw." That's the fragility: the base class's implementation has become part of its contract without anyone deciding so.

2.2 Other ways a base class breaks its subclasses

Self-use is the best-known route, but not the only one. Each of these has caused real bugs:

  • New methods in the base. A subclass enforces "every element is non-null" by overriding add and addAll. A later version of the base class adds addFirst, and the subclass doesn't override it, so nulls get in through the new door. Java 21's SequencedCollection added exactly such methods (addFirst, addLast) to existing list types. Any subclass guarding inserts had a new unguarded method the day it upgraded.
  • Name clashes. The subclass has a helper size(int) and the base later adds a method with the same signature. The subclass now overrides it by accident, or fails to compile.
  • Overridable calls from constructors. The base constructor calls init(), which the subclass overrides. It runs before the subclass's fields are set, so it sees nulls and zeros. The JavaScript Set example above is this bug in a standard library.
  • Protected fields. Subclasses read and write the base's protected state directly, so the base can't change its representation without breaking them. A protected field is public to everyone who extends you.
  • Changed defaults. A base method's default behaviour changes ("now trims whitespace"). Subclasses that call super.method() and then do their own processing change behaviour without being edited.

All five share the same shape: the subclass is coupled to the base class's implementation, not just its interface. Composition removes that channel entirely, because a wrapper sees only the public methods of the object it holds.

Design for inheritance, or prohibit it

Bloch's Item 19 says a class meant to be extended must document its self-use ("this method calls add for each element") and keep it stable forever, which is a heavy commitment. Classes not designed for extension should prevent it: final in Java, sealed hierarchies, or at least a docstring in Python and TypeScript, which have no enforced final (Python's typing.final is checked only by type checkers). Kotlin makes classes final by default for exactly this reason.

3. Delegation and forwarding

The composed classes above use delegation: an object holds a reference to another and forwards calls to it, sometimes adding behaviour before or after. It's the basic mechanism behind composition, and behind patterns like Decorator, Proxy and Adapter.

Delegation has a cost that inheritance hides: you have to write the forwarding methods. If you need a wrapper that is a full Set, implementing every Set method by hand is tedious. The usual answers:

  • Expose only what's needed. The CountingSet above has five methods, not the forty on Set. Often a smaller surface is a feature. See Interfaces & API Design at Class Level.
  • Write the forwarding class once. Bloch's ForwardingSet implements Set by forwarding everything to a wrapped instance. Wrappers then extend ForwardingSet and override only what they change. This is inheritance, but from a class designed for it, whose self-use is trivial (none).
  • Use language support. Kotlin's class CountingSet(inner: MutableSet<T>) : MutableSet<T> by inner generates the forwarding. Python's __getattr__ can forward unknown attributes, though it hides the interface from readers and type checkers, so use it sparingly. Lombok's @Delegate does the same for Java.
  • Extend a skeletal base. AbstractSet, AbstractList and Python's collections.abc.MutableMapping exist so you implement a few primitives and get the rest, with documented self-use.

3.1 The self problem

One subtle limit of wrappers: when the wrapped object passes this to someone else, such as registering itself as a callback, it passes itself, not the wrapper. Calls through that reference skip the wrapper. Bloch calls this the SELF problem. It mostly matters for listener and callback frameworks. If an object registers itself somewhere, wrapping it won't intercept those calls.

4. Strategy by composition

The second big win of composition is handling variation along several independent dimensions. Inheritance can only vary one dimension per level, so combinations multiply.

Consider game characters. Each has a way of moving (walk, fly, swim) and a weapon (sword, bow, staff). With inheritance, every combination is a class: 3 × 3 = 9 classes, and adding a fourth weapon adds three more. Worse, a character can't change its movement at runtime when it picks up wings, because an object can't change its class.

classDiagram
    class Character {
        <<abstract>>
        +describe() String
    }
    Character <|-- WalkingSwordsman
    Character <|-- WalkingArcher
    Character <|-- FlyingSwordsman
    Character <|-- FlyingArcher
    Character <|-- SwimmingArcher
    note for Character "One class per combination: 3 movements x 3 weapons = 9 classes"

With composition, each dimension is its own small interface, and a character has one of each:

classDiagram
    class Hero {
        -String name
        -Movement movement
        -Weapon weapon
        +describe() String
        +equip(Weapon w)
        +learn(Movement m)
    }
    class Movement {
        <<interface>>
        +move() String
    }
    class Weapon {
        <<interface>>
        +attack() String
    }
    Hero o-- Movement
    Hero o-- Weapon
    Movement <|.. Walk
    Movement <|.. Fly
    Weapon <|.. Sword
    Weapon <|.. Bow

Now 3 + 3 = 6 small classes cover all nine combinations, a new weapon is one class, and behaviour can change at runtime.

// ---------- before: one subclass per combination ----------
abstract class Character {
    abstract String describe();
}
class WalkingSwordsman extends Character { String describe() { return "walks, slashes"; } }
class FlyingSwordsman extends Character { String describe() { return "flies, slashes"; } }
class WalkingArcher extends Character { String describe() { return "walks, shoots"; } }
class FlyingArcher extends Character { String describe() { return "flies, shoots"; } }
// ...and five more for swim and staff. A walking archer can never learn to fly.

// ---------- after: one small interface per dimension ----------
interface Movement { String move(); }
interface Weapon { String attack(); }

final class Walk implements Movement { public String move() { return "walks"; } }
final class Fly implements Movement { public String move() { return "flies"; } }
final class Sword implements Weapon { public String attack() { return "slashes"; } }
final class Bow implements Weapon { public String attack() { return "shoots"; } }

final class Hero {
    private final String name;
    private Movement movement;
    private Weapon weapon;

    Hero(String name, Movement movement, Weapon weapon) {
        this.name = name; this.movement = movement; this.weapon = weapon;
    }
    void equip(Weapon w) { weapon = w; }
    void learn(Movement m) { movement = m; }
    String describe() { return name + " " + movement.move() + ", " + weapon.attack(); }
}

class StrategyCompositionDemo {
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) {
        check(new FlyingArcher().describe().equals("flies, shoots"), "before works, but is fixed");

        Hero ana = new Hero("Ana", new Walk(), new Sword());
        check(ana.describe().equals("Ana walks, slashes"), "initial");
        ana.learn(new Fly());
        ana.equip(new Bow());
        check(ana.describe().equals("Ana flies, shoots"), "changed at runtime");

        Weapon staff = () -> "casts";   // a new weapon is one lambda or class, nothing else changes
        ana.equip(staff);
        check(ana.describe().equals("Ana flies, casts"), "new weapon");
        System.out.println(ana.describe());
    }
}
from typing import Protocol


# ---------- before: one subclass per combination ----------
class Character:
    def describe(self) -> str:
        raise NotImplementedError


class WalkingSwordsman(Character):
    def describe(self) -> str:
        return "walks, slashes"


class FlyingArcher(Character):
    def describe(self) -> str:
        return "flies, shoots"
# ...and seven more. A walking swordsman can never pick up a bow.


# ---------- after: one small protocol per dimension ----------
class Movement(Protocol):
    def move(self) -> str: ...


class Weapon(Protocol):
    def attack(self) -> str: ...


class Walk:
    def move(self) -> str:
        return "walks"


class Fly:
    def move(self) -> str:
        return "flies"


class Sword:
    def attack(self) -> str:
        return "slashes"


class Bow:
    def attack(self) -> str:
        return "shoots"


class Hero:
    def __init__(self, name: str, movement: Movement, weapon: Weapon) -> None:
        self._name, self._movement, self._weapon = name, movement, weapon

    def equip(self, weapon: Weapon) -> None:
        self._weapon = weapon

    def learn(self, movement: Movement) -> None:
        self._movement = movement

    def describe(self) -> str:
        return f"{self._name} {self._movement.move()}, {self._weapon.attack()}"


class Staff:
    def attack(self) -> str:
        return "casts"


assert FlyingArcher().describe() == "flies, shoots"
ana = Hero("Ana", Walk(), Sword())
assert ana.describe() == "Ana walks, slashes"
ana.learn(Fly())
ana.equip(Bow())
assert ana.describe() == "Ana flies, shoots"
ana.equip(Staff())
assert ana.describe() == "Ana flies, casts"
print(ana.describe())
function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(what);
}

// ---------- before: one subclass per combination ----------
abstract class Character {
  abstract describe(): string;
}
class WalkingSwordsman extends Character { describe(): string { return "walks, slashes"; } }
class FlyingArcher extends Character { describe(): string { return "flies, shoots"; } }
// ...and seven more. Neither can change what it is.

// ---------- after: one small interface per dimension ----------
interface Movement { move(): string }
interface Weapon { attack(): string }

const walk: Movement = { move: () => "walks" };
const fly: Movement = { move: () => "flies" };
const sword: Weapon = { attack: () => "slashes" };
const bow: Weapon = { attack: () => "shoots" };

class Hero {
  constructor(private readonly name: string, private movement: Movement, private weapon: Weapon) {}
  equip(w: Weapon): void { this.weapon = w; }
  learn(m: Movement): void { this.movement = m; }
  describe(): string { return `${this.name} ${this.movement.move()}, ${this.weapon.attack()}`; }
}

check(new FlyingArcher().describe() === "flies, shoots", "before: fixed combination");
check(new WalkingSwordsman().describe() === "walks, slashes", "before: another class");
const ana = new Hero("Ana", walk, sword);
check(ana.describe() === "Ana walks, slashes", "initial");
ana.learn(fly);
ana.equip(bow);
check(ana.describe() === "Ana flies, shoots", "changed at runtime");
ana.equip({ attack: () => "casts" });
check(ana.describe() === "Ana flies, casts", "new weapon");
console.log(ana.describe());

This is the Strategy pattern: each dimension of variation becomes an object the main class delegates to. It's the same move as in the parking-lot classic, where pricing varies by vehicle and time of day. Model PricingPolicy as a collaborator, not HourlyCarTicket extends CarTicket.

Don't over-split

Composition is for dimensions that actually vary. If every character always walks, Movement is speculation. See DRY, KISS & YAGNI. The skill is to spot the real axes of change in the requirements, which is often a noun phrase like "different pricing for different vehicle types" or "users can choose how they're notified."

5. Mixins and traits

Sometimes you want to give many unrelated classes the same small capability, like "can be described", "has a version" or "can be compared by key". Inheritance from a common base doesn't fit, because the classes have nothing else in common and may already have a base. Delegation works but means forwarding in every class. Mixins and traits sit in between: units of reusable behaviour that are combined into a class rather than inherited as its identity.

Each language does this differently:

LanguageMechanismState allowed?Conflict resolution
JavaInterfaces with default methods (Java 8+)No instance fields: defaults call abstract accessorsIf two interfaces supply the same default, the class must override it and can pick one with A.super.m()
PythonMixin classes via multiple inheritanceYesMethod resolution order (C3 linearisation) decides. Inspect it with Cls.__mro__
TypeScriptFunctions that take a class and return a subclassYesThe last mixin applied wins
Scala, Rust, PHPReal traitsVariesExplicit, language-defined
import java.util.*;

// Traits as interfaces with default methods. No fields: they build on abstract accessors.
interface Describable {
    Map<String, Object> fields();
    default String describe() {
        StringBuilder sb = new StringBuilder();
        new TreeMap<>(fields()).forEach((k, v) -> sb.append(sb.isEmpty() ? "" : ", ").append(k).append('=').append(v));
        return sb.toString();
    }
}

interface Versioned {
    int version();
    default boolean isNewerThan(Versioned other) { return version() > other.version(); }
}

record Doc(String title, int version) implements Describable, Versioned {
    public Map<String, Object> fields() { return Map.of("title", title, "version", version); }
}

record Config(String key, String value, int version) implements Versioned {}

class TraitDemo {
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) {
        Doc v1 = new Doc("spec", 1), v2 = new Doc("spec", 2);
        check(v2.isNewerThan(v1) && !v1.isNewerThan(v2), "versioned trait");
        check(v2.describe().equals("title=spec, version=2"), "describable trait");
        check(new Config("theme", "dark", 3).isNewerThan(v2), "unrelated classes share the trait");
        System.out.println(v2.describe());
    }
}
class DescribeMixin:
    def describe(self) -> str:
        return ", ".join(f"{k}={v}" for k, v in sorted(vars(self).items()))


class VersionedMixin:
    version: int

    def bump(self) -> None:
        self.version += 1

    def is_newer_than(self, other: "VersionedMixin") -> bool:
        return self.version > other.version


class Doc(DescribeMixin, VersionedMixin):
    def __init__(self, title: str) -> None:
        self.title = title
        self.version = 1


class Config(VersionedMixin):
    def __init__(self, key: str) -> None:
        self.key = key
        self.version = 5


a, b = Doc("spec"), Doc("spec")
b.bump()
assert b.is_newer_than(a) and not a.is_newer_than(b)
assert b.describe() == "title=spec, version=2"
assert Config("theme").is_newer_than(b)
assert [c.__name__ for c in Doc.__mro__] == ["Doc", "DescribeMixin", "VersionedMixin", "object"]
print(b.describe())
function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(what);
}

type Ctor<T = object> = new (...args: any[]) => T;

function Versioned<TBase extends Ctor>(Base: TBase) {
  return class extends Base {
    version = 1;
    bump(): void { this.version++; }
    isNewerThan(other: { version: number }): boolean { return this.version > other.version; }
  };
}

function Describable<TBase extends Ctor>(Base: TBase) {
  return class extends Base {
    describe(): string {
      return Object.entries(this).map(([k, v]) => `${k}=${String(v)}`).sort().join(", ");
    }
  };
}

class Doc { constructor(public title: string) {} }
class Config { constructor(public key: string) {} }

const VersionedDoc = Describable(Versioned(Doc));
const VersionedConfig = Versioned(Config);

const a = new VersionedDoc("spec");
const b = new VersionedDoc("spec");
b.bump();
check(b.isNewerThan(a) && !a.isNewerThan(b), "versioned mixin");
check(b.describe() === "title=spec, version=2", "describable mixin");
const c = new VersionedConfig("theme");
c.bump(); c.bump(); c.bump();
check(c.isNewerThan(b), "unrelated class shares the mixin");
console.log(b.describe());

Mixins are composition at the class level rather than the object level: you still decide behaviour when the class is written, not at runtime. They're good for small, orthogonal capabilities. They go wrong in predictable ways:

  • State collisions. Two Python mixins that both set self.version silently share one attribute. Java avoids this by not allowing state in interfaces.
  • Hidden ordering. In Python, swapping the order of bases changes which method wins. In TypeScript, the outermost mixin wins. Readers rarely check.
  • Dependency on the host. VersionedMixin assumes the host class defines version. Nothing enforces that at runtime in Python. Java's version makes the dependency an abstract method, which is clearer.
  • Mixin piles. A class built from seven mixins is as hard to follow as a seven-level hierarchy. If you need many, the class probably has too many responsibilities.

6. When inheritance is the right tool

"Favour" is not "always". Inheritance is the better choice when these conditions hold together:

  1. It's a genuine is-a relationship in behaviour, not just in naming. Every subclass can stand in for the base anywhere, keeping its contract. This is the LSP test, covered below.
  2. The base class is designed for extension. It documents which methods are hooks, what they're called by, and keeps everything else final.
  3. The hierarchy is shallow and closed, or owned by one team. Two levels in one module is manageable. Five levels across three teams is where fragility bites.
  4. The variation is the identity of the object. A Circle doesn't become a Square at runtime. A character's weapon, by contrast, does change.

Typical good uses:

UseWhy inheritance fits
Framework extension points (HttpServlet, Thread, test base classes, Android Activity)The framework designed the base for subclassing and documents the hooks. This is the Template Method pattern
Exception hierarchiesCatch-by-type relies on subtyping, and exceptions carry little behaviour. See Error Handling in Object Design
Closed sets of variants (AST nodes, shapes, payment events)A sealed hierarchy plus exhaustive matching is clean and safe
Skeletal implementations (AbstractList, collections.abc.Mapping)The base documents exactly which primitives you implement and how the rest use them

Here's inheritance done well: a base class designed for extension with a template method. The algorithm is final. Subclasses fill in one required hook and may override one optional hook. Nothing else is overridable, so there's no hidden self-use for subclasses to trip over.

import java.util.*;

abstract class Exporter {
    // The algorithm is final: subclasses cannot change the order or skip steps.
    final String export(List<List<String>> rows) {
        StringBuilder out = new StringBuilder(header());
        for (List<String> row : rows) out.append(formatRow(row)).append('\n');
        return out.toString();
    }

    /** Required hook: format one row. Called once per row, in order. */
    protected abstract String formatRow(List<String> row);

    /** Optional hook: text before the first row. Called once. Default: nothing. */
    protected String header() { return ""; }
}

final class CsvExporter extends Exporter {
    protected String formatRow(List<String> row) { return String.join(",", row); }
    @Override protected String header() { return "name,qty\n"; }
}

final class TsvExporter extends Exporter {
    protected String formatRow(List<String> row) { return String.join("\t", row); }
}

class TemplateMethodDemo {
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) {
        List<List<String>> rows = List.of(List.of("tea", "2"), List.of("cake", "1"));
        check(new CsvExporter().export(rows).equals("name,qty\ntea,2\ncake,1\n"), "csv");
        check(new TsvExporter().export(rows).equals("tea\t2\ncake\t1\n"), "tsv");
        System.out.print(new CsvExporter().export(rows));
    }
}
from abc import ABC, abstractmethod
from typing import final


class Exporter(ABC):
    @final  # checked by type checkers such as mypy, not at runtime
    def export(self, rows: list[list[str]]) -> str:
        return self.header() + "".join(self.format_row(row) + "\n" for row in rows)

    @abstractmethod
    def format_row(self, row: list[str]) -> str:
        """Required hook: format one row. Called once per row, in order."""

    def header(self) -> str:
        """Optional hook: text before the first row. Called once."""
        return ""


class CsvExporter(Exporter):
    def format_row(self, row: list[str]) -> str:
        return ",".join(row)

    def header(self) -> str:
        return "name,qty\n"


class TsvExporter(Exporter):
    def format_row(self, row: list[str]) -> str:
        return "\t".join(row)


rows = [["tea", "2"], ["cake", "1"]]
assert CsvExporter().export(rows) == "name,qty\ntea,2\ncake,1\n"
assert TsvExporter().export(rows) == "tea\t2\ncake\t1\n"
try:
    Exporter()  # type: ignore[abstract]
    raise AssertionError("abstract class instantiated")
except TypeError:
    pass
print(CsvExporter().export(rows), end="")
function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(what);
}

abstract class Exporter {
  // TypeScript has no `final`: document that export() is not meant to be overridden.
  export(rows: string[][]): string {
    return this.header() + rows.map((r) => this.formatRow(r) + "\n").join("");
  }
  /** Required hook: format one row. Called once per row, in order. */
  protected abstract formatRow(row: string[]): string;
  /** Optional hook: text before the first row. Called once. */
  protected header(): string { return ""; }
}

class CsvExporter extends Exporter {
  protected formatRow(row: string[]): string { return row.join(","); }
  protected override header(): string { return "name,qty\n"; }
}

class TsvExporter extends Exporter {
  protected formatRow(row: string[]): string { return row.join("\t"); }
}

const rows = [["tea", "2"], ["cake", "1"]];
check(new CsvExporter().export(rows) === "name,qty\ntea,2\ncake,1\n", "csv");
check(new TsvExporter().export(rows) === "tea\t2\ncake\t1\n", "tsv");
console.log(new CsvExporter().export(rows));

The difference from the fragile examples is that the base class publishes its self-use: "export calls header once and formatRow once per row." That sentence is part of the contract, so the base author can't change it casually, and the subclass author can rely on it.

7. How this relates to Liskov substitution

The Liskov Substitution Principle says a subtype must be usable anywhere its base type is expected without breaking callers. It explains a lot of composition-over-inheritance advice:

  • Inheritance makes a promise of substitutability, whether you meant it or not. class Stack extends Vector tells every caller "a Stack is a Vector," so they can call insertElementAt(x, 0) on it.
  • If you can't keep the whole base contract, you shouldn't inherit. You only wanted the storage, so compose.
  • Composition makes no substitutability promise, so it can't violate LSP. You choose which interface, if any, the new class implements.

The JDK has a well-known example. java.util.Stack extends Vector (from Java 1.0), so a "stack" exposes add(index, element), remove(index) and get(index). The Javadoc now recommends Deque instead. java.util.Properties extends Hashtable<Object, Object>, so you can put non-string values into something documented as string-to-string, after which getProperty returns null for those keys. Both are cases where implementation reuse was wanted and subtyping came along uninvited.

import java.util.*;

// ---------- before: java.util.Stack inherits Vector's whole API ----------
// ---------- after: a stack that owns a Deque and exposes only stack operations ----------
final class LifoStack<E> {
    private final Deque<E> items = new ArrayDeque<>();
    void push(E e) { items.push(e); }
    E pop() {
        if (items.isEmpty()) throw new NoSuchElementException("stack is empty");
        return items.pop();
    }
    Optional<E> peek() { return Optional.ofNullable(items.peek()); }
    int size() { return items.size(); }
}

class StackDemo {
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) {
        Stack<String> jdk = new Stack<>();
        jdk.push("a"); jdk.push("b");
        jdk.add(0, "sneaky");                  // legal: Stack is a Vector
        jdk.remove(1);                         // removes "a" from the middle
        check(jdk.pop().equals("b") && jdk.pop().equals("sneaky"), "before: LIFO order broken");

        LifoStack<String> stack = new LifoStack<>();
        stack.push("a"); stack.push("b");
        check(stack.pop().equals("b") && stack.pop().equals("a"), "after: only LIFO operations exist");
        check(stack.peek().isEmpty(), "empty");
        System.out.println("composed stack keeps its invariant");
    }
}
# ---------- before: inherit from list, get every list operation ----------
class ListStack(list):
    def push(self, item: str) -> None:
        self.append(item)


s = ListStack()
s.push("a")
s.push("b")
s.insert(0, "sneaky")       # legal: a ListStack is a list
s.sort(reverse=True)        # also legal, and reorders the stack
assert s.pop() == "a"       # not the last thing pushed


# ---------- after: own a list, expose only stack operations ----------
class Stack:
    def __init__(self) -> None:
        self._items: list[str] = []

    def push(self, item: str) -> None:
        self._items.append(item)

    def pop(self) -> str:
        if not self._items:
            raise IndexError("stack is empty")
        return self._items.pop()

    def peek(self) -> str | None:
        return self._items[-1] if self._items else None

    def __len__(self) -> int:
        return len(self._items)


t = Stack()
t.push("a")
t.push("b")
assert not hasattr(t, "insert") and not hasattr(t, "sort")
assert t.pop() == "b" and t.pop() == "a" and t.peek() is None
print("composed stack keeps its invariant")
function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(what);
}

// ---------- before: extend Array, get every array operation ----------
class ArrayStack<T> extends Array<T> {}

const s = new ArrayStack<string>();
s.push("a", "b");
s.unshift("sneaky"); // legal: an ArrayStack is an Array
s.reverse();         // also legal
check(s.pop() === "sneaky", "before: LIFO broken");

// ---------- after: own an array, expose only stack operations ----------
class Stack<T> {
  readonly #items: T[] = [];
  push(item: T): void { this.#items.push(item); }
  pop(): T {
    const top = this.#items.pop();
    if (top === undefined) throw new RangeError("stack is empty");
    return top;
  }
  peek(): T | undefined { return this.#items[this.#items.length - 1]; }
  get size(): number { return this.#items.length; }
}

const t = new Stack<string>();
t.push("a");
t.push("b");
check(t.pop() === "b" && t.pop() === "a" && t.peek() === undefined, "after: LIFO kept");
console.log("composed stack keeps its invariant");

A practical test before you write extends: read the base class's public API, method by method, and ask whether every method makes sense on your subclass and keeps its invariants. If even one doesn't ("you can insert into the middle of my stack"), inheritance is the wrong tool.

8. When composition goes too far

Composition is the safer default, but over-applied it has its own costs:

Over-applicationSymptomBetter
Composing what is genuinely a closed variant setShape holds an AreaStrategy and a PerimeterStrategy, chosen separately, so you can build a circle with a square's perimeterA sealed hierarchy: the variants are the type
Forwarding boilerplate everywhereDozens of one-line foo() { return inner.foo(); } methodsA skeletal base class, language delegation (by in Kotlin), or a smaller interface
Too many tiny objectsEvery concept is three objects wired together, and understanding one behaviour means opening six filesMerge collaborators that always change together (cohesion beats granularity)
Fighting the frameworkWrapping a framework type that's designed to be subclassed (a test base class, a servlet)Extend it. That's what it's for
Rebuilding exception hierarchies by compositionAn Error with an ErrorKind field and a switch on it in every handlerSubclass exceptions so catch can dispatch by type
Identity confusionA wrapper isn't equals to what it wraps, and callbacks reach the inner objectDocument it. Don't wrap objects that register themselves as listeners

The heuristic: compose across axes that vary independently or change at runtime; inherit within a closed, designed-for-extension family.

9. Refactoring a hierarchy into composition

You'll often inherit, so to speak, a hierarchy that's already gone wrong. In an interview this shows up as "here's some existing code, the interviewer wants a new variant, and the hierarchy doesn't fit." The refactor is mechanical if you take it in small steps:

  1. Find the axes. List the subclasses and ask what actually differs between them. In the character example, two things differ: movement and weapon. Each independent axis becomes an interface.
  2. Extract the varying behaviour. For each axis, move the overridden methods out of the subclasses into small classes that implement the new interface. FlyingArcher.move() becomes Fly.move().
  3. Give the base class fields for the collaborators. The former base class now has a Movement and a Weapon and delegates to them. Pass them in through the constructor.
  4. Replace subclass construction with composition. new FlyingArcher() becomes new Hero("…", new Fly(), new Bow()). If many call sites built the same combinations, a small factory method can name them: Hero.archer(name).
  5. Delete the empty subclasses. Once nothing overrides anything, the subclasses are just names for combinations. Remove them or keep them as factory methods.
  6. Make the remaining class final. The point of the refactor is that variation now happens through collaborators. Closing the class stops the hierarchy from growing back.

Each step keeps the code compiling and the tests passing, which matters in a machine-coding round where you can't afford a broken build for twenty minutes.

The reverse refactor exists too. If you composed a Shape from separately chosen area and perimeter strategies, and you notice that every valid shape uses exactly one matching pair, then the strategies aren't independent. The "axes" were really one axis, the shape kind. Collapse them into a sealed hierarchy where each variant implements both methods.

10. Common mistakes

  • Using inheritance to share a utility method. class OrderService extends BaseService just to get log() and now(). That's not an is-a relationship. Inject a logger and a clock instead, which also makes the class testable.
  • Inheriting to change one detail. class CachedRepository extends SqlRepository overriding find to check a cache. Every other method is now coupled to SqlRepository's internals. A Decorator that wraps any Repository is cleaner and works with every implementation.
  • Encoding state as type. ActiveUser, SuspendedUser, DeletedUser as subclasses. Users change status, but objects can't change class. Use a status field, or the State pattern if behaviour differs a lot per status.
  • Overriding to disable. A subclass that overrides a base method to throw UnsupportedOperationException is announcing an LSP violation. Split the interface instead.
  • Deep hierarchies "for organisation". Entity → Auditable → Versioned → Document → Invoice. Each layer adds coupling. Flatten it, and turn the cross-cutting layers into traits or composed collaborators.
  • Composing everything by reflex. Wrapping a framework base class that's built for subclassing, or turning a closed set of shape types into strategy soup. Composition is the default, not a rule.

11. How it shows up in LLD interviews

Inheritance overuse is one of the most common LLD mistakes, and interviewers probe for it.

Typical prompts where it matters:

  • Parking lot: Vehicle with Car, Bike, Truck subclasses is fine if they differ in behaviour. If the only difference is which spot size they need, an enum or a size field is simpler. Pricing should be a composed policy, not CarTicket versus TruckTicket.
  • Employee and payroll systems: SalariedEmployee extends Employee breaks when someone moves from hourly to salaried. An Employee with a PayPolicy handles it. An object can't change class, but it can change a field.
  • Notification systems: EmailNotifier, SmsNotifier and then EmailAndSmsNotifier is the combinatorial explosion. A list of channels composed together isn't.
  • Game characters, vehicles with features, coffee with add-ons: these are multi-dimensional variation, which suits composition, or Decorator for stacked add-ons.
  • Shapes, chess pieces, AST nodes: these are closed variant sets where inheritance (or a sealed hierarchy) is natural.

What to say:

  • "I'm using an interface for PricingPolicy and composing it into the lot, because pricing varies independently of vehicle type and might change at runtime."
  • "Vehicle subclasses are fine here because each one really behaves differently, and the set is closed. I'll make them final."
  • "I'd avoid PremiumMember extends Member. Membership tier changes over time, so it's state or a composed policy, not a type."
  • "Before extending, I check that every method of the base makes sense on the subclass. Here Queue.remove(index) wouldn't, so I'm composing."

Follow-ups to expect:

  • "What's the fragile base class problem?" Have the addAll example ready.
  • "Why not just make it a subclass?" Answer with runtime change, combinations, or base-contract mismatch.
  • "When would you use inheritance?" Closed variants, framework hooks, exceptions, designed-for-extension bases.
  • "How does this relate to LSP?" Inheritance promises substitutability. Composition doesn't.

12. Quick decision guide

flowchart TD
    A["Do I want to reuse or vary behaviour?"] --> B{"Is the new class substitutable for the base in every method?"}
    B -->|"No"| C["Compose: hold the object, expose what you need"]
    B -->|"Yes"| D{"Can the behaviour change at runtime, or vary on several axes?"}
    D -->|"Yes"| E["Compose: strategy objects, one per axis"]
    D -->|"No"| F{"Is the base designed and documented for extension?"}
    F -->|"No"| G["Compose, or ask the owner to design hooks"]
    F -->|"Yes"| H["Inherit, keep it shallow, make leaf classes final"]

13. Interview questions

  1. "What does 'favour composition over inheritance' actually mean?" Inheritance couples a subclass to its base's implementation and fixes behaviour at compile time. Composition couples only to a public interface and allows runtime change. Default to composition, and choose inheritance deliberately when there's a real, designed-for subtype relationship.

  2. "Explain the fragile base class problem with an example." A subclass of HashSet overrides add and addAll to count insertions. Because HashSet.addAll internally calls add, bulk inserts are counted twice. The subclass depends on an undocumented implementation detail, and the base class could change it in a later release. Wrapping a Set and forwarding avoids it.

  3. "How would you model an employee who can switch from hourly to salaried?" Give Employee a PayPolicy field with HourlyPay and SalariedPay implementations. Switching is a field assignment. With subclasses you'd have to create a new object and copy state, which breaks identity and references.

  4. "When is inheritance the right choice?" When the subclass is truly substitutable everywhere, the variant set is closed or the base is designed for extension with documented hooks, the hierarchy is shallow, and the variation is part of the object's identity. Framework extension points, exception hierarchies and sealed variant families are typical.

  5. "What's the difference between a mixin and composition?" A mixin adds behaviour to a class at definition time, through multiple inheritance or a class-returning function. Object composition adds behaviour by holding another object, so it can change at runtime and doesn't share namespace. Mixins suit small orthogonal capabilities, while composition suits real collaborators.

  6. "Why is java.util.Stack considered a design mistake?" It extends Vector, so it inherits indexed insert, remove and get, which let callers violate LIFO order. It was implementation reuse disguised as a subtype. A stack that holds a Deque and exposes only push, pop and peek keeps its invariant. The Javadoc itself recommends Deque.

  7. "Doesn't composition lead to lots of boilerplate?" Some. Forwarding methods are the price. Reduce it by exposing a smaller interface, using a reusable forwarding base or skeletal implementation, or language features like Kotlin's by. The boilerplate is visible and boring, while fragile base class bugs are invisible and expensive.

  8. "How does LSP relate to this principle?" LSP says subtypes must honour their base type's contract. Inheritance creates a subtype automatically, so it makes that promise even when you only wanted code reuse. If you can't keep the base's whole contract, you should compose instead.

  9. "Your design has Bird with fly(), and now you need Penguin. What do you do?" Don't override fly() to throw, since that breaks LSP. Either split the capability out (Bird plus a Flyer interface only for birds that fly) or compose a Movement strategy. The LSP page walks through this case.

  10. "How do you make a class safe to extend?" Document every self-use ("addAll calls add for each element") and keep it stable. Make non-hook methods final. Don't call overridable methods from constructors. Prefer a template method with explicit hooks. If you don't want to make those commitments, make the class final.