Object-oriented basics · Chapter 3

Inheritance vs composition

When a class should extend another and when it should hold parts instead. The class explosion, the fragile base class, and favour composition, with Java and Python code.

IntermediateInterview priority: High45 min
On this page
  1. The problem: a family tree that keeps growing
  2. The idea: "is a" versus "has a"
  3. How it works in code
  4. The fragile base class problem
  5. Options and trade-offs
  6. When inheritance is the right call
  7. In the interview
  8. Quiz

The problem: a family tree that keeps growing

A toy company models robots. Some walk, some fly; some have a claw, some a laser. The first design uses inheritance for everything: a base Robot, then WalkingRobot and FlyingRobot, then WalkingClawRobot, WalkingLaserRobot, FlyingClawRobot, FlyingLaserRobot.

Then marketing adds swimming and a camera. Three ways to move times three tools is nine classes; add a third feature with two options and it is eighteen. Worse, the "walk" code is copied into every walking class, and a robot that should switch from walking to flying mid-game can't, because an object cannot change its class.

One subclass per combination: the class explosion

  1. But inheritance gets out of hand. A toy company makes robots that walk or fly, with a claw or a laser. One subclass per combination… then add swimming and a camera. This is a class explosion.

The idea: "is a" versus "has a"

Inheritance lets a class (the subclass, or child) reuse and extend another (the superclass, or parent). The subclass gets the parent's fields and methods and can override methods to do its own version. It models an "is a" relationship: a Dog is an Animal.

A Dog is an Animal, and overrides speak()

  1. Inheritance lets one class reuse another. A Dog is an Animal, so Dog extends Animal and gets its name and eat() for free.
  2. A subclass can override a method to do its own version. Call speak() on any animal and you get the right sound.

Composition builds an object from other objects it holds as fields. It models "has a": a Robot has a Mover and has a Tool, and delegates to them (calls their methods to do the work). Each part is a small class behind an interface, and any combination is just a different set of parts.

A robot built from parts, swapped at run time

  1. Composition builds a robot from parts instead. A Robot has a Mover and has a Tool. Each part is a small class, and you plug in any combination.
  2. Parts can even be swapped while the program runs: robot.setMover(new Fly()). An object can never change its class, but it can change its parts. That’s why the rule of thumb is: favour composition over inheritance.

With composition, three movers and three tools are six small classes, not nine robot classes, and new features add classes linearly rather than multiplying them.

How it works in code

Inheritance, done properly

abstract class Animal {
    private final String name;                      // private: subclasses use name()

    protected Animal(String name) { this.name = name; }

    public String name() { return name; }

    public String eat() { return name + " eats"; }  // shared behaviour, inherited as is

    public abstract String speak();                  // every animal must provide its own
}

class Dog extends Animal {
    Dog(String name) { super(name); }               // run the parent's constructor first

    @Override
    public String speak() { return name() + " says woof"; }
}

class Cat extends Animal {
    Cat(String name) { super(name); }

    @Override
    public String speak() { return name() + " says meow"; }

    @Override
    public String eat() { return super.eat() + ", slowly"; }   // extend, not replace
}

super(...) runs the parent's constructor; super.eat() (Python super().eat()) calls the parent's version of an overridden method. The @Override annotation makes the compiler check you really are overriding something, which catches typos like speek().

Composition: the robot

interface Mover { String move(); }
interface Tool  { String use(); }

class Walk implements Mover { public String move() { return "walks"; } }
class Fly  implements Mover { public String move() { return "flies"; } }
class Swim implements Mover { public String move() { return "swims"; } }

class Claw  implements Tool { public String use() { return "grabs with a claw"; } }
class Laser implements Tool { public String use() { return "fires a laser"; } }

class Robot {
    private final String name;
    private Mover mover;                 // has a Mover
    private final Tool tool;             // has a Tool

    Robot(String name, Mover mover, Tool tool) {
        this.name = name; this.mover = mover; this.tool = tool;
    }

    void setMover(Mover mover) { this.mover = mover; }   // swap a part at run time

    String act() { return name + " " + mover.move() + " and " + tool.use(); }  // delegate
}

public class Main {
    public static void main(String[] args) {
        Robot r = new Robot("R2", new Walk(), new Claw());
        System.out.println(r.act());     // R2 walks and grabs with a claw
        r.setMover(new Fly());
        System.out.println(r.act());     // R2 flies and grabs with a claw
        System.out.println(new Robot("Nemo", new Swim(), new Laser()).act());
    }
}

This is the Strategy pattern in miniature: each part is a strategy the robot delegates to.

The fragile base class problem

Inheritance has a subtler cost than class counts. A subclass depends not only on what the parent's methods promise, but on how they are implemented. When the parent changes its internals, a subclass that was correct yesterday breaks today, even though nobody touched it. This is the fragile base class problem.

The classic example (from Joshua Bloch's Effective Java): count how many items were ever added to a set by extending HashSet.

import java.util.*;

class CountingSet<E> extends HashSet<E> {
    private int added = 0;

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

    @Override public boolean addAll(Collection<? extends E> c) {
        added += c.size();
        return super.addAll(c);          // surprise: HashSet's addAll calls add() for each item
    }

    int added() { return added; }
}

CountingSet<String> s = new CountingSet<>();
s.addAll(List.of("a", "b", "c"));
System.out.println(s.added());           // 6, not 3: every item was counted twice

Delete the addAll override and it works, but only by relying on HashSet's current implementation. If a future version made addAll stop calling add, the count would silently drop to 0 for bulk adds. Either way, the subclass is correct only by accident.

Composition removes the dependency on internals: wrap a set instead of extending one, and count in your own methods.

import java.util.*;

class CountingSet<E> {
    private final Set<E> inner = new HashSet<>();   // has a Set
    private int added = 0;

    public boolean add(E e) { added++; return inner.add(e); }

    public boolean addAll(Collection<? extends E> c) {
        boolean changed = false;
        for (E e : c) changed |= add(e);             // our own add: counted exactly once
        return changed;
    }

    public boolean contains(Object o) { return inner.contains(o); }
    public int size() { return inner.size(); }
    public int added() { return added; }
}

The wrapper exposes only the methods it needs. If callers need the full Set interface, write a forwarding class that implements Set and passes each method through (Guava ships ForwardingSet for exactly this).

Options and trade-offs

Inheritance (extends)Composition (has a)Interface (implements)
RelationshipX is a Y, alwaysX has a YX can do Y
Good atSharing code and a type in one step; abstract base classes with a templateMixing independent features; swapping behaviour at run timeLetting unrelated classes be used the same way
Weak atCombinations, run-time change, coupling to the parent's internalsForwarding boilerplate, more objectsSharing state or a lot of code
Changes at run time?No: an object never changes classYes: swap the partFixed per class
Use whenA stable "is a" with real shared behaviour (often a framework base class)Features vary independently or change oftenYou need a type many classes can fill

The test from the chapter: would "X is a Y" be true everywhere and always? A Square is a Rectangle in geometry, but if Rectangle has setWidth, a square that keeps its sides equal breaks code that sets width and height separately. That is a Liskov substitution failure, and a sign the relationship is not really "is a" in code.

Inheritance is still right for a true "is a"

  1. Inheritance is still right for a true “is a” with shared behaviour, like Dog and Animal. The test: would “X is a Y” always be true, everywhere? If it’s really “X has a Y” or “X can do Y”, use composition or an interface.

When inheritance is the right call

  • A true, stable "is a" with shared behaviour: Dog and Animal, IOException and Exception.
  • Frameworks designed for it: HttpServlet, Android's Activity, Python's unittest.TestCase. The base class documents which methods to override.
  • Template Method: a base class fixes the steps of an algorithm and subclasses fill in a few (see the Template Method pattern).
  • Closed families: Java sealed classes (sealed interface Shape permits Circle, Square) let you inherit safely within one module because nobody else can extend.

If you write a class meant to be extended, document which methods call which (Bloch: "design and document for inheritance, or else prohibit it"). Otherwise mark it final.

Multiple inheritance, mixins and the MRO

Java allows one superclass but many interfaces; since Java 8, interfaces can carry default methods, and if two interfaces supply the same default the class must override it and choose (A.super.m()). Python allows multiple base classes. It resolves methods using the method resolution order (MRO), a C3 linearisation you can print with Cls.__mro__, and super() means "the next class in the MRO", not "my parent". That makes small mixins (a class adding one capability, such as JsonMixin with to_json()) practical, as long as each one calls super().__init__(**kwargs) cooperatively. Mixins are still inheritance: keep them stateless and narrow.

In the interview

Your turn: a notification system

Messages go out by email, SMS or push. Some must also be logged, some retried up to three times, some both. A colleague proposes EmailNotifier, LoggedEmailNotifier, RetryingEmailNotifier, LoggedRetryingEmailNotifier, and the same for SMS and push. Propose a better design with Java and Python code.

Compare with our answer

Each channel is one class behind a Notifier interface; logging and retrying are wrappers that have a Notifier and are themselves Notifiers, so they stack in any order. This is composition, and the stacking wrappers are the Decorator pattern.

interface Notifier { void send(String to, String msg); }

class EmailNotifier implements Notifier {
    public void send(String to, String msg) { System.out.println("email " + to + ": " + msg); }
}

class Logged implements Notifier {
    private final Notifier inner;
    Logged(Notifier inner) { this.inner = inner; }
    public void send(String to, String msg) {
        System.out.println("log: sending to " + to);
        inner.send(to, msg);
    }
}

class Retrying implements Notifier {
    private final Notifier inner;
    private final int attempts;
    Retrying(Notifier inner, int attempts) { this.inner = inner; this.attempts = attempts; }
    public void send(String to, String msg) {
        for (int i = 1; ; i++) {
            try { inner.send(to, msg); return; }
            catch (RuntimeException e) { if (i >= attempts) throw e; }
        }
    }
}

Notifier n = new Logged(new Retrying(new EmailNotifier(), 3));

A strong answer mentions: one Notifier interface · one class per channel · logging and retrying as wrappers that hold a Notifier · wrappers stacking in any order, so classes grow additively (3 channels + 2 features = 5 classes, not 12) · retries only being safe if sending twice is harmless (idempotency).

Your turn: the requirement changes

Your game has class Player extends Character and class Enemy extends Character. Now some enemies can be recruited and become the player's allies mid-game, keeping their health and inventory. What goes wrong, and how do you redesign?

Compare with our answer

An object can't change its class, so an Enemy can't become an ally without copying all its state into a new object (and every reference to the old one goes stale). "Enemy" is not what the character is, it is a role it has right now.

A strong answer mentions: an object cannot change class · modelling allegiance as a field or a part (Faction, or a Controller that is player-driven or AI-driven) · Character holding health and inventory once · swapping the part at run time · keeping inheritance only for real "is a" differences, if any remain.

Inheritance vs composition on one page
  • Inheritance = "is a", shares code and type; composition = "has a", delegates to parts; interface = "can do".
  • Favour composition: features that vary independently, behaviour swapped at run time, code you don't own.
  • Class explosion: n × m subclasses for combinations; composition needs n + m parts.
  • Fragile base class: subclasses depend on the parent's implementation (the HashSet.addAll double count).
  • Don't call overridable methods from constructors; keep fields private, not protected; keep hierarchies shallow.
  • Inheritance is right for a stable "is a" with real shared behaviour, framework base classes, Template Method, sealed families.
  • Design for inheritance or mark the class final.
  • Composition's costs: forwarding boilerplate, more objects, the "self problem" with callbacks.
Interactive labPractise it: build robots from partsOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. A coffee app has Coffee, MilkCoffee, SugarCoffee and MilkSugarCoffee subclasses. Oat milk, syrup and extra shots are coming next. What should you do?

2. A class extends HashSet and overrides both add and addAll to count items. Adding three items with addAll reports 6. Why?

3. Animal's constructor calls describe(). Dog overrides describe() to print its breed field, set in Dog's constructor. What is printed when you create a Dog?

4. Which relationship is the best fit for inheritance?

5. In a game, characters can switch between walking, flying and swimming many times during one level. Which design handles this best?

6. What is the main reason to mark a class final (or document it carefully) if it was not designed to be extended?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.