Skip to content
Composition over Inheritance — Explained with Examples

Composition over Inheritance — Explained with Examples

DodaTech Updated Jun 15, 2026 2 min read

Composition over Inheritance is a principle that favors assembling behavior from small, reusable components over inheriting functionality from parent classes.

Composition over Inheritance is a design guideline that recommends using composition (has-a relationships) instead of inheritance (is-a relationships) to achieve code reuse. The Gang of Four popularized it: “Favor object composition over class inheritance.”

Why It Matters

Inheritance creates tight coupling between parent and child classes. A change in the parent can break all children. Deep inheritance hierarchies become rigid and hard to understand. Composition builds systems from small, interchangeable parts — each part can be modified, replaced, or tested independently.

Real-World Analogy

A LEGO set vs a pre-assembled toy. The pre-assembled toy (inheritance) comes as one piece — if the arm breaks, you need a whole new toy. LEGO bricks (composition) let you swap a red brick for a blue one, add a wheel, or rebuild entirely. More flexible, more reusable.

Example: Inheritance vs Composition

# Inheritance approach — rigid hierarchy
class Animal:
    def make_sound(self): pass

class Dog(Animal):
    def make_sound(self): return "Woof"

class Cat(Animal):
    def make_sound(self): return "Meow"

# What if we need a robot dog? Can't inherit both Robot and Dog
# Composition approach — flexible building blocks
class SoundBehavior:
    def __init__(self, sound):
        self.sound = sound
    def make_sound(self):
        return self.sound

class MoveBehavior:
    def __init__(self, mode):
        self.mode = mode
    def move(self):
        return f"Moving by {self.mode}"

class Robot:
    def __init__(self, sound_behavior, move_behavior):
        self.sound = sound_behavior
        self.move = move_behavior

# Compose different combinations
dog_robot = Robot(SoundBehavior("Woof"), MoveBehavior("legs"))
cat_robot = Robot(SoundBehavior("Meow"), MoveBehavior("legs"))
drone = Robot(SoundBehavior("Buzz"), MoveBehavior("flying"))

print(dog_robot.sound.make_sound())  # Woof
print(drone.move.move())             # Moving by flying

Related Terms

Encapsulation, Law of Demeter, Dependency Inversion Principle

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro