Composition vs Inheritance
45 min · Intermediate
Inheritance says a class is a kind of another class; composition says a class has a part that does some of its work. Interviewers ask when to use each, why "favour composition" is common advice, and to refactor an inheritance design into composition on the spot.
Topics in this lesson
- IS-A vs HAS-A; association, aggregation, composition
- Why favour composition: the fragile base class
- Refactor an inheritance hierarchy to composition
- Follow-up questions: when inheritance is right
Interview questions this lesson answers
- What is the difference between IS-A and HAS-A?
- What is composition?
- What is aggregation?
- What is association?
- What does "favour composition over inheritance" mean?
- What is the fragile base class problem?
- Give a concrete example of the fragile base class problem.
- How does composition fix that example?
- What is delegation?
- What is a forwarding or wrapper class?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.