Skip to lesson

Composition vs inheritance: choosing

"Favour composition over inheritance" is one of the best-known rules in OOP. It means: when both extends and a HAS-A field could do the job, choose the field. Inheritance is not banned; it is just the stronger, riskier tool.

What the rule really says

"Favour composition over inheritance" is a design rule: when both a HAS-A field and extends could reuse code, choose the field and delegate to it. Keep inheritance for a true, stable IS-A.

Both tools reuse code. With inheritance the child gets the parent's code automatically; with composition the whole holds the other object in a field and delegates (opens in a new tab) to it.

Java
class InheritedCounter extends NumberList {   // gets every NumberList method    private int added;    void add(int x) {        added++;        super.add(x);    }}class ComposedCounter {                       // holds a NumberList and delegates    private NumberList list = new NumberList();    private int added;    void add(int x) {        added++;        list.add(x);    }}

Inheritance ties the child to every public method of the parent, to its inner workings, and for the object's whole life. Composition ties the whole only to the methods it actually calls. So start with composition, and use inheritance only when a true IS-A passes every check in this lesson.

A real bug: the fragile base class

The fragile base class problem is when a child class breaks because of how its parent works inside, or because that inside changes later, even though the child's own code did not change.

NumberList.addAll simply calls add for each number. CountingList extends NumberList overrides both methods to count how many numbers went in. Add 2 numbers with addAll, and the count says 4.

Example 1 · The double-counting bug

FragileDemo.javaJava
class NumberList {    private int[] items = new int[20];    private int size;
    void add(int x) {        items[size] = x;        size++;    }
    void addAll(int[] xs) {        for (int x : xs) {            add(x);        }    }
    int size() { return size; }}
class CountingList extends NumberList {    private int added;
    @Override    void add(int x) {        added++;        super.add(x);    }
    @Override    void addAll(int[] xs) {        added = added + xs.length;        super.addAll(xs);    }
    int getAdded() { return added; }}
public class FragileDemo {    public static void main(String[] args) {        CountingList list = new CountingList();        list.addAll(new int[] { 10, 20, 30 });        System.out.println("Size: " + list.size());        System.out.println("Added: " + list.getAdded());    }}
Output
Size: 3
Added: 6

What this code does

  • Our addAll counts 3, then super.addAll calls add three times. Dynamic dispatch runs our overridden add, which counts 3 more.
  • Nothing in NumberList's methods warned us that addAll uses add. The child depends on the parent's hidden inside: the fragile base class problem.

Example 2 · The fix: count with composition

CountFixDemo.javaJava
class NumberList {    private int[] items = new int[20];    private int size;
    void add(int x) {        items[size] = x;        size++;    }
    void addAll(int[] xs) {        for (int x : xs) {            add(x);        }    }
    int size() { return size; }}
class CountingList {    private NumberList list = new NumberList();    private int added;
    void add(int x) {        added++;        list.add(x);    }
    void addAll(int[] xs) {        added = added + xs.length;        list.addAll(xs);    }
    int size() { return list.size(); }    int getAdded() { return added; }}
public class CountFixDemo {    public static void main(String[] args) {        CountingList list = new CountingList();        list.addAll(new int[] { 10, 20, 30 });        list.add(40);        System.out.println("Size: " + list.size());        System.out.println("Added: " + list.getAdded());    }}
Output
Size: 4
Added: 4

What this code does

  • When the inner NumberList.addAll calls add, it calls its own add. Our counting code is outside and never runs twice.
  • The class has the same methods as before, so callers do not change. Only extends became a private field plus forwarding.

The child broke because of a detail of the parent it could not see, and it breaks again if the parent changes that detail. With composition, the inner list calls its own add, so your counting code runs once.

Trace the code

Watch the count go wrong

class NumberList {
int size;
void add(int x) { size++; }
void addAll(int[] xs) {
for (int x : xs) {
add(x);
}
}
}
class CountingList extends NumberList {
int added;
void add(int x) { added++; super.add(x); }
void addAll(int[] xs) { added += xs.length; super.addAll(xs); }
}
public class FragileTrace {
public static void main(String[] args) {
CountingList list = new CountingList();
list.addAll(new int[] { 10, 20 });
System.out.println("Size " + list.size + ", added " + list.added);
}
}

Variables

size
0
added
0

Output

(nothing printed yet)

Line 19A CountingList object starts with size 0 and added 0.

Step 1 of 7
Deleting your addAll override fixes the count today, but only because addAll happens to call add. If a later NumberList stops doing that, bulk adds are not counted at all.

More costs of inheritance

"A penguin is a bird" is true in English. But if Bird promises fly(), Penguin must either fly or throw, and code that trusts every Bird crashes.

Example 3 · A promise the child cannot keep

PenguinDemo.javaJava
class Bird {    private String name;
    Bird(String name) { this.name = name; }
    String getName() { return name; }
    void fly() {        System.out.println(name + " is flying");    }}
class Penguin extends Bird {    Penguin() { super("Penguin"); }
    @Override    void fly() {        throw new UnsupportedOperationException("Penguins cannot fly");    }}
public class PenguinDemo {    public static void main(String[] args) {        Bird[] birds = { new Bird("Sparrow"), new Penguin(), new Bird("Parrot") };        for (Bird b : birds) {            b.fly();        }    }}
Sample output
Sparrow is flying
Exception in thread "main" java.lang.UnsupportedOperationException: Penguins cannot fly
	at Penguin.fly(PenguinDemo.java:18)
	at PenguinDemo.main(PenguinDemo.java:26)

What this code does

  • "A penguin is a bird" is true in English, but Bird promises fly(), and Penguin cannot keep that promise. Code that trusts Bird crashes.
  • The child must do everything the parent does without breaking. Here it fails, so this inheritance is wrong.

This is the second IS-A check from HAS-A vs IS-A (opens in a new tab). Three more costs:

  • All or nothing: the child gets every public parent method, even ones that break its rules (stack.removeAt(0)).
  • Fixed for life: an object cannot change its class, so an intern object can never become a full-time one.
  • One parent only: mixing features (SMS, email × normal, urgent) needs a subclass for every combination.

When inheritance is the right choice

Inheritance is right when the IS-A sentence is true, the child can do everything the parent promises without throwing, and the relationship will not change while the program runs.

Example 4 · Fixing it: share what is true, add abilities with interfaces

BirdFixDemo.javaJava
interface Flyer {    void fly();}
abstract class Bird {    private String name;
    Bird(String name) { this.name = name; }
    String getName() { return name; }
    void eat() { System.out.println(name + " is eating"); }}
class Sparrow extends Bird implements Flyer {    Sparrow() { super("Sparrow"); }
    public void fly() { System.out.println(getName() + " is flying"); }}
class Penguin extends Bird {    Penguin() { super("Penguin"); }
    void swim() { System.out.println(getName() + " is swimming"); }}
public class BirdFixDemo {    public static void main(String[] args) {        Bird[] birds = { new Sparrow(), new Penguin() };        for (Bird b : birds) {            b.eat();        }        Flyer[] flyers = { new Sparrow() };        for (Flyer f : flyers) {            f.fly();        }        new Penguin().swim();    }}
Output
Sparrow is eating
Penguin is eating
Sparrow is flying
Penguin is swimming

What this code does

  • Bird now promises only what every bird can do (eat). Inheritance is fine here: every child keeps every promise.
  • Flying became an ability, the Flyer interface, given only to birds that can fly. No method has to throw.

Good cases: a custom exception like InvalidMarksException extends Exception, an abstract class designed to be extended like Shape with area(), and small, stable families. When the parent was not written to be extended and you want only some of its code, use a field.

Refactoring extends into a field

You can turn an inheritance design into composition in a few safe steps, and callers barely notice. When the part must change while the program runs, give it an interface type and a setter.

Example 5 · A role that changes: composition with a setter

PromoteDemo.javaJava
interface PayRule {    int monthlyPay();    String title();}
class InternPay implements PayRule {    public int monthlyPay() { return 15000; }    public String title() { return "Intern"; }}
class FullTimePay implements PayRule {    private int salary;
    FullTimePay(int salary) { this.salary = salary; }
    public int monthlyPay() { return salary; }    public String title() { return "Full-time"; }}
class Employee {    private String name;    private PayRule rule;
    Employee(String name, PayRule rule) {        this.name = name;        this.rule = rule;    }
    void promote(PayRule newRule) { rule = newRule; }
    void payslip() {        System.out.println(name + " (" + rule.title() + "): Rs. " + rule.monthlyPay());    }}
public class PromoteDemo {    public static void main(String[] args) {        Employee diya = new Employee("Diya", new InternPay());        diya.payslip();        diya.promote(new FullTimePay(60000));        diya.payslip();    }}
Output
Diya (Intern): Rs. 15000
Diya (Full-time): Rs. 60000

What this code does

  • With class Intern extends Employee, Diya's object could never stop being an Intern; you would have to build a new object and copy everything.
  • Here the changing part (how she is paid) is a delegate. promote swaps it, and it is still the same Employee object.

The steps:

  1. Replace extends Parent with a private Parent field.
  2. Write forwarding methods only for what callers need.
  3. Drop the methods that would break the class's rules.
  4. If the behaviour must change at run time, make the field an interface type with a setter, as above.

Next step

Check your understanding

12 quick questions