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.
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:
| Inheritance | Composition | |
|---|---|---|
| Question it answers | Is B a kind of A? | Does B have an A, or use one? |
| Link is fixed | At compile time | Can be swapped at run time |
| Coupling | Tight: child depends on parent internals | Loose: depends only on an interface |
| Reuse by | Extending | Holding 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