Lesson 6: Composition over inheritance
public class Car : Engine looks like a handy shortcut — until you discover every engine method leaks onto the car, every engine change breaks the car, and a car with two engine kinds becomes impossible. In this lesson we replace the inheritance with a field: the car will hold an engine instead of be
Composition is like a toolbox: instead of being born a 'hammer-man', a professional holds a hammer and swaps it when needed. Inheritance welds the hammer to the hand forever.
- composition over inheritance
- When the real relationship is has-a, hold the object as a private field and delegate to it — instead of inheriting and dragging a fragile hierarchy and a leaking API.
- has-a relationship
- A relationship where an object holds another object as a field and uses it — as opposed to is-a, where a class inherits and claims to be a kind of its base.