Concept · Core

Composition over Inheritance

Inheritance locks behaviour in at compile time and explodes combinatorially. Composition — “has-a” — keeps it swappable. Prefer it.

Asked atAmazonGoogleMetaAtlassian
step 1 / 10
1/2The inheritance trap
Robot
+ move()
WalkingRobot
+ move(): walk
FlyingRobot
+ move(): fly
WalkingFlyingRobot
+ move(): ??
The inheritance trap
1class Robot { void move(){} }
2class WalkingRobot extends Robot { void move(){ walk(); } }
3class FlyingRobot extends Robot { void move(){ fly(); } }
4// need walk + fly? extends BOTH → impossible

Start with a Robot base class that declares move(). Reasonable so far.