Lego, not a family tree

Composition over Inheritance

The analogy

A family tree is fixed — you cannot pick new parents later. Lego is not: you snap an engine on, swap it for a bigger one, pull it off. Building an object from smaller parts it OWNS is usually more flexible than being born into a long family line.

Visualizer

Snapping parts on and off

step 1 / 4
CAR — owns its parts (has-a)
engine: PetrolEngine
wheels: Wheel × 4
stereo: BasicStereo
PARTS SHELF — swappable
ElectricEngine
PremiumStereo
RoofRack

The car does not inherit an engine. It holds one.

class Car:
    def __init__(self, engine):
        self.engine = engine      # HAS-A

    def swap_engine(self, engine):
        self.engine = engine      # at runtime

car = Car(PetrolEngine())
car.swap_engine(ElectricEngine())
Check yourself

Car HAS an Engine is…