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
- How do you implement a Singleton, and why is it often considered an anti-pattern?
- Explain the SOLID principles.
- What is a design pattern, and why are they useful?
- What is the difference between dependency inversion, dependency injection and inversion of control?
- What is dependency injection, and what forms does it take?
- Explain the Factory Method pattern and how it differs from a simple factory.
- What problem does the Builder pattern solve? Show an example.
- What is the Adapter pattern? Give an example.