Design Patterns interview question · Most asked

Why is composition often preferred over inheritance?

Summary

Composition (an object holds other objects it delegates to) lets you combine behaviours freely and change them at runtime, without the class explosion and tight coupling of deep inheritance hierarchies.

Longer Answer

Using inheritance to mix features (walking, flying, swimming robots) needs a subclass per combination, couples every subclass to its parent's internals (the fragile base class problem), and fixes behaviour at compile time. With composition, a Robot holds a Movement object, so three movement classes cover every robot and a robot can switch movement at runtime.

Inheritance is still right for genuine "is-a" relationships with stable shared behaviour, such as a framework's base controller.

Key Points

  • Avoids class explosion for combinations.
  • Allows runtime changes.
  • Looser coupling than base classes.
  • Inheritance still fits real is-a relationships.

Deep dive: Design Patterns, Explained Simply: Program to Interfaces, Favour Composition

Explanation

What interviewers look for

Concrete reasons (combinations, runtime change, fragile base class) and a balanced view of when inheritance is fine.

Follow-up questions

  • Which patterns are built on composition?

More most-asked Design Patterns questions

← All Design Patterns questions