# Composition vs Inheritance in Java — The Fragile Base Class Problem and How to Choose

Source: https://skills101.in/learn/oops/oop-composition-vs-inheritance — Skills101 free tutorial (OOP Concepts). Updated 2026-11-21.

You have probably heard "**favour composition over inheritance**". Most students repeat it in interviews without being able to say *why*. This lesson shows a real bug that inheritance causes, fixes it with composition, and ends with a simple checklist for choosing between the two.

Quick definitions first:

- **Inheritance** (`class B extends A`): B **is an** A. B gets all of A's fields and methods and can override them.
- **Composition**: class B **has an** A in a field and calls it to do part of the work. This calling-through is called **delegation**.

## 1. A bug caused by inheritance

The placement cell wants a set of registered students that also **counts how many times** students were added (for a report). A student writes the obvious subclass of `HashSet`:

```java
import java.util.*;

class CountingSet extends HashSet<String> {
    private int addCount = 0;

    @Override
    public boolean add(String s) {
        addCount++;
        return super.add(s);
    }

    @Override
    public boolean addAll(Collection<? extends String> c) {
        addCount += c.size();
        return super.addAll(c);
    }

    int getAddCount() { return addCount; }
}

public class Main {
    public static void main(String[] args) {
        CountingSet set = new CountingSet();
        set.addAll(List.of("Asha", "Ravi", "Neha"));
        System.out.println("Students: " + set.size());
        System.out.println("Add count: " + set.getAddCount());
    }
}
```

```text
Students: 3
Add count: 6
```

We added three names, but the count says **6**. Why? Inside the JDK, `HashSet.addAll()` (inherited from `AbstractCollection`) works by calling `add()` once for each element. Because we overrode `add()`, each of those calls **also** increased the counter. Our `addAll` counted 3, then the three hidden `add` calls counted 3 more.

![Fragile base class: CountingSet.addAll adds 3 to the count, then calls HashSet.addAll, which calls the overridden add three times, adding 3 more, for a wrong total of 6](https://skills101.in/learn-img/oops/fragile-base-class.svg)

This is the **fragile base class problem**: a subclass depends on **internal details** of its parent that are not part of its documented contract. Fixing it by deleting our `addAll` override would "work" today, but if a future JDK changed `addAll` to not call `add`, the count would silently become wrong the other way. With inheritance, you can never be sure.

This example comes from Joshua Bloch's book *Effective Java*, which is where the advice "favour composition over inheritance" is explained in detail.

## 2. The same feature with composition

Instead of **being** a `HashSet`, our class **has** a `Set` and forwards calls to it. It implements only the methods it needs:

```java
import java.util.*;

class CountingSet {
    private final Set<String> inner = new HashSet<>();   // composition: has-a Set
    private int addCount = 0;

    boolean add(String s) {
        addCount++;
        return inner.add(s);                              // delegation
    }

    boolean addAll(Collection<String> c) {
        addCount += c.size();
        return inner.addAll(c);    // inner's add() is HashSet's own, not ours — no double count
    }

    int size() { return inner.size(); }
    int getAddCount() { return addCount; }
}

public class Main {
    public static void main(String[] args) {
        CountingSet set = new CountingSet();
        set.addAll(List.of("Asha", "Ravi", "Neha"));
        set.add("Asha");                                  // duplicate: counted, but not stored twice
        System.out.println("Students: " + set.size());
        System.out.println("Add count: " + set.getAddCount());
    }
}
```

```text
Students: 3
Add count: 4
```

Now `inner.addAll()` calls `inner`'s own `add()`, which we did not override, so nothing is counted twice. Our class no longer depends on how `HashSet` works inside — only on its public behaviour.

In real projects you would also make it `implements Set<String>` so it can be passed anywhere a `Set` is expected. A class that implements an interface and forwards every call to a wrapped object is called a **wrapper** or **forwarding** class — the same idea as the Decorator pattern from the previous lesson.

## 3. Mixing behaviours: where inheritance runs out

A college sports app has players with different abilities. With inheritance you might write `Player → Runner`, `Player → Swimmer`. Now a triathlete needs to run **and** swim. Java does not allow `extends Runner, Swimmer`, and creating `RunnerSwimmer`, `RunnerCyclist`, … for every mix explodes.

With composition, each ability is an object, and a player **has a list** of them:

```java
import java.util.*;

interface Ability { String perform(String who); }

class Running implements Ability {
    public String perform(String who) { return who + " runs 5 km"; }
}

class Swimming implements Ability {
    public String perform(String who) { return who + " swims 1 km"; }
}

class Player {
    private final String name;
    private final List<Ability> abilities = new ArrayList<>();
    Player(String name) { this.name = name; }
    Player add(Ability a) { abilities.add(a); return this; }
    void train() {
        for (Ability a : abilities) System.out.println(a.perform(name));
    }
}

public class Main {
    public static void main(String[] args) {
        new Player("Asha").add(new Running()).train();
        new Player("Ravi").add(new Running()).add(new Swimming()).train();
        // abilities can even be added while the program runs
        Player neha = new Player("Neha");
        neha.add(who -> who + " cycles 20 km");
        neha.train();
    }
}
```

```text
Asha runs 5 km
Ravi runs 5 km
Ravi swims 1 km
Neha cycles 20 km
```

Composition lets you **combine** behaviours freely and even change them at runtime. Inheritance fixes one parent at compile time.

## 4. When inheritance IS the right choice

Inheritance is not bad. It is right when **all** of these are true:

1. There is a real **is-a** relationship: a `SavingsAccount` is a `BankAccount`.
2. The subclass can be used anywhere the parent is used without surprises (Liskov substitution).
3. The parent class was **designed for extension** — its documentation says which methods are safe to override (for example, abstract classes and template methods), or you own both classes.

Good examples: `class InvalidMarksException extends RuntimeException`, an abstract `Shape` with `Circle` and `Rectangle`, framework hooks like `HttpServlet.doGet()`.

![Comparison of inheritance and composition by relationship, coupling to the parent, when the link is fixed, combining behaviours and typical example](https://skills101.in/learn-img/oops/inherit-vs-compose.svg)

| Question | If yes → |
|---|---|
| Is it truly "B **is an** A" in every situation? | inheritance may fit |
| Do you only want to **reuse some code** of A? | composition |
| Do you need to **combine** several behaviours? | composition |
| Must the behaviour **change at runtime**? | composition |
| Is A a class you don't control (JDK, library) that wasn't designed for subclassing? | composition |

## Common mistakes

- Extending a class only to reuse a couple of its methods ("`Stack extends Vector`" is a famous design mistake in the JDK: a stack should not allow inserting in the middle, but it inherits `insertElementAt`).
- Overriding a method of a library class and assuming you know which other methods call it internally.
- Deep inheritance chains (five or six levels) where nobody knows which class a method comes from.
- Saying "composition is always better". The correct answer is: prefer composition by default; use inheritance for genuine is-a relationships with classes designed for it.

## Quick recap

- Inheritance = is-a and tight coupling to the parent's internals; composition = has-a plus delegation through public methods.
- The `CountingSet` bug (count 6 instead of 3) is the fragile base class problem: `addAll` secretly calls the overridden `add`.
- Composition avoids it, lets you combine behaviours and change them at runtime.
- Use inheritance for true is-a relationships with classes designed for extension; otherwise compose.


Practice quiz and free certificate: https://skills101.in/learn/oops/oop-composition-vs-inheritance