teacher
Sign in

Composition over Inheritance

Build objects out of smaller parts they hold and delegate to, instead of stacking subclasses, and learn when inheritance is still right.

25 min3 interactive

The problem it solves

Say you have game units, and each unit moves one way (walks, flies) and attacks one way (sword, fireball). With inheritance you might write WalkingKnight, FlyingKnight, WalkingMage, FlyingMage. Add one new movement and you double the classes. This is called class explosion.

Two relationships can connect classes:

InheritanceComposition
Question it answersIs B a kind of A?Does B have an A, or use one?
Link is fixedAt compile timeCan be swapped at run time
CouplingTight: child depends on parent internalsLoose: depends only on an interface
Reuse byExtendingHolding a part and delegating (forwarding calls to it)

The advice "favour composition over inheritance" does not say never inherit. It says: reach for a held part first.

1 of 5