Composition Versus Inheritance

Most programs reuse classes instead of writing every behaviour from scratch. Object-oriented languages give you two main ways to do that: build a new class on top of an existing one, or build it out of existing objects. The choice decides how easily your code absorbs new requirements, and you will make it in nearly every design with more than a few classes.

Two ways to reuse a class

Inheritance defines a new class, the subclass, as a specialised version of an existing superclass: the subclass receives every attribute and method of the superclass and may override some of them. It models an is-a relationship: a Car is a Vehicle.


Composition builds a class by storing references to objects of other classes in its fields and asking those objects to do part of the work. It models a has-a relationship: a Car has an Engine. Passing a call along to the held object is called delegation.


Python
class Engine:
    def start(self):
        return 'engine running'

class Vehicle:
    def describe(self):
        return 'a vehicle'

class Car(Vehicle):                 # inheritance: a Car is a Vehicle
    def __init__(self):
        self.engine = Engine()      # composition: a Car has an Engine

    def start(self):
        return self.engine.start()  # delegation to the held Engine


Calling Car().describe() runs the inherited method, while Car().start() runs the engine's method through delegation.


Two class diagrams: Car inherits from Vehicle through an arrow with a hollow triangle, and Car holds an Engine through a line with a filled diamond.


Choosing with the substitution test

Inheritance fits when the subclass truly is a kind of the superclass, and a subclass object must work correctly anywhere the program expects a superclass object. This is the Liskov substitution principle. Wanting to reuse a few methods is not enough on its own: if some inherited methods make no sense for the new class, or would let callers break its rules, hold an object instead and delegate to it.


Example: a Square that inherits from Rectangle also inherits set_width and set_height. Code that sets a rectangle's width to 4 and then its height to 2 expects an area of 8. A square that keeps its sides equal changes both dimensions each time, ends with sides of 2 and reports an area of 4. The square passes the everyday is-a test but fails the substitution test.


Feature

Inheritance

Composition

Relationship modelled

is-a

has-a

When the link is fixed

When the class is written

Can change at run time by assigning another object

Coupling

Subclass depends on superclass internals

Container depends only on the component's public methods

Methods the reusing class exposes

Every public method of the superclass

Only the methods it chooses to forward

Typical cost

Fragile base class: superclass changes break subclasses

Extra forwarding methods to write



Combining independent variations

When objects vary along several independent dimensions, inheritance needs one concrete subclass for every combination, while composition needs one component class per option. With mm options in one dimension and nn in another:


Ninheritance=m×nNcomposition=m+nN_{\text{inheritance}} = m \times n \qquad N_{\text{composition}} = m + n


Here NcompositionN_{\text{composition}} counts the component classes only, not the class that holds them. With more dimensions the pattern extends: m×n×pm \times n \times p against m+n+pm + n + p.


Example: drawing software with 3 shapes and 4 fill styles needs 3×4=123 \times 4 = 12 subclasses such as RedCircle and StripedSquare under inheritance. With composition, each shape holds a FillStyle object, so you write 3 shape classes and 4 style classes, 7 in total. Adding a fifth style costs 3 new subclasses under inheritance but only 1 new class under composition.



What to remember

  • Inheritance models is-a and fixes the link when you write the class; composition models has-a and can swap parts at run time.
  • Inherit only when a subclass object can stand in for a superclass object everywhere, not merely to reuse a few methods.
  • Overriding methods that the superclass calls internally can break it; delegation avoids that coupling.
  • For independent variations, inheritance grows as a product (m×nm \times n) and composition as a sum (m+nm + n).

Example: Configuring a delivery robot

A robotics team writes software for delivery robots. Each robot uses one of 4 locomotion systems (wheels, tracks, legs, propellers) and one of 5 navigation sensors (lidar, camera, ultrasonic, GPS, infrared). Every combination must be supported.


a) If the team uses inheritance and writes one concrete subclass, such as WheeledLidarRobot, for every combination, how many concrete robot subclasses are needed?


Each locomotion system pairs with every sensor, so each locomotion system needs ________ subclasses, one per sensor. The count is the product of the option counts:


Ninheritance=m×n=4×5=20N_{\text{inheritance}} = m \times n = 4 \times 5 = 20


The inheritance design needs 20 concrete robot subclasses, before counting any shared base class.


b) Instead, a Robot class holds a locomotion field and a sensor field. Each field refers to an object whose class inherits from an abstract Locomotion or Sensor base class. Counting Robot and both abstract base classes, how many classes does this design need in total?


Composition needs one component class per option: 4 locomotion classes plus 5 sensor classes, so there are ________ concrete component classes. Add the Robot class and the two abstract bases:


N=(4+5)+1+2=12N = (4 + 5) + 1 + 2 = 12


The composed design needs 12 classes in total, fewer than the 20 subclasses of part a), and the gap widens as options are added.


c) The team later adds 2 new locomotion systems and 1 new sensor. How many new classes must be written under each design?


Under inheritance the option counts become 4 + 2 = ________ locomotion systems and 5 + 1 = ________ sensors. The new total is 6 × 6 = ________ subclasses, so the number of new subclasses is:


36−20=1636 - 20 = 16


Under composition each new option is one new component class, and Robot and the abstract bases do not change:


2+1=32 + 1 = 3


Inheritance needs 16 new classes; composition needs 3.


d) A robot driving on wheels must switch to its propellers when it reaches a river, without being replaced by a new robot object. Write the Robot methods that make this possible in the composed design, and explain why the inheritance design cannot do it the same way.


The robot stores its locomotion part in a field and delegates movement to whatever object that field currently holds:


Python
class Robot:
    def __init__(self, locomotion, sensor):
        self.locomotion = locomotion
        self.sensor = sensor

    def move(self, metres):
        return self.locomotion.move(metres)  # delegate to the current part

    def set_locomotion(self, locomotion):
        self.locomotion = locomotion


Create the robot with robot = Robot(Wheels(), Lidar()), then call robot.set_locomotion(Propellers()) at the river. After the reassignment, the next call to robot.move(50) delegates to the ________ object, while the same robot keeps its sensor and any other state.


In the inheritance design, wheels are built into the class WheeledLidarRobot, and an object's class is fixed when it is created. Switching would mean building a new PropellerLidarRobot and copying all the state across. Composition turns the choice of locomotion into data that can change at run time.

Match each object-oriented design term on the left with the description on the right that defines it correctly.

Match each term
A.

A change inside a superclass silently breaks subclasses that depend on its internal behaviour

B.

A class stores references to other objects in its fields and builds its behaviour from them

C.

A subclass receives the attributes and methods of a superclass and may replace some of them

D.

Code written for a superclass works correctly when it is given a subclass object

E.

An object forwards a method call to another object it holds

F.

A subclass supplies its own version of a method it would otherwise receive unchanged

Fragile base class problem

Substitutability

Inheritance

Composition

Delegation

Overriding

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Read each design description and fill in the reuse idea it shows. Each blank takes a single word.


A SavingsAccount can be passed to any method that expects a BankAccount and still behaves correctly there. It passes the is-a test, so the natural reuse mechanism is .


A Car keeps an Engine object in a private field, which passes the has-a test, so the reuse mechanism is . When Car.start() does nothing but call engine.start(), the car is handing the work to its part, a technique called .


A Square class extends a mutable Rectangle class, and its setWidth method also changes the height. Code written for rectangles, which expects the height to stay the same, now gives wrong areas, so this subclass breaks .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A developer writes a stack class in Python by inheriting from the built-in list:


Python
class Stack(list):
    def push(self, item):
        self.append(item)

    def peek(self):
        return self[-1]


The inherited pop() removes the top item correctly. However, client code can also call inherited methods such as insert(0, x) and sort(), or write s[2] = x, and each of these breaks last-in-first-out order. Which redesign best guarantees that clients can use only stack operations?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice