Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Object-Oriented Programming

    Composition Over Inheritance

    Composition — building a class by holding other objects as fields and delegating work to them: a "has-a" relationship.

    Chapter 7 of 123 min read

    The Plain Picture#

    A car has an engine — it isn't a kind of engine. If you want a car with a better engine, you swap the engine. You don't redesign the whole car family tree.

    The Real Names#

    • Composition = building a class by holding other objects as fields and delegating work to them: a "has-a" relationship.

    • "Favour composition over inheritance" — one of the most quoted design guidelines (from the Design Patterns book, 1994).

    • The problem it avoids: the fragile base class — changes to a parent class silently break subclasses that depend on its internals.

    Under the Hood#

    The inheritance trap. Suppose StudyBuddy needs quizzes that are timed, quizzes that are proctored, and quizzes that are both:

                      Quiz
              ┌────────┴─────────┐
          TimedQuiz         ProctoredQuiz
              │
       TimedProctoredQuiz ?? — must extend both. Java can't. And each new feature doubles the classes.

    With composition:

    Java
    interface Timer {
        boolean expired();
    }
    
    interface Proctor {
        boolean suspicious(String studentId);
    }
    
    class Quiz {
        private final List<Question> questions;
        private final Timer timer; // HAS a timer   (could be a "no-limit" timer)
        private final Proctor proctor; // HAS a proctor (could be a "does nothing" proctor)
    
        Quiz(List<Question> questions, Timer timer, Proctor proctor) {
            this.questions = questions;
            this.timer = timer;
            this.proctor = proctor;
        }
    
        boolean canSubmit(String studentId) {
            return !timer.expired() && !proctor.suspicious(studentId); // DELEGATE to the parts
        }
    }

    Any combination of features is just different parts passed in. Parts can even change at runtime. And each part is easy to test in isolation with a fake.

    When inheritance is right#

    Use inheritance when all of these hold:

    1. it's a true is-a relationship that won't change (a MultipleChoice really is a Question);

    2. the subclass can be used anywhere the parent is expected without surprises (the Liskov Substitution Principle, SOLID Principles);

    3. you control both classes, or the parent was designed to be extended.

    Otherwise, compose.

    Check yourself

    4 questions
    1

    "Is-a" vs "has-a" — which is inheritance, which is composition?

    Show answer

    Is-a = inheritance; has-a = composition.

    2

    Why does inheritance struggle with "timed + proctored" quizzes?

    Show answer

    Each combination needs its own subclass (and Java has single inheritance), so classes multiply; composition just combines parts.

    3

    What's the fragile base class problem?

    Show answer

    Changes inside a parent class unexpectedly break subclasses that depend on its behaviour or internals.

    4

    When is inheritance a good choice?

    Show answer

    For a stable, true is-a relationship where the subclass can fully substitute for the parent, and the parent was designed for extension.