When do you prefer composition over inheritance?medium
Answer
Prefer composition when you want to reuse behaviour without committing to a rigid class hierarchy. "Has-a" relationships are usually better modeled with composition than "is-a" inheritance.
Explanation
Inheritance tightly couples child to parent - changes in the parent ripple down. Composition lets you swap implementations at runtime and combine behaviours from multiple sources. The Gang of Four principle "favour composition over inheritance" reflects that inheritance hierarchies tend to grow brittle as requirements change.
Follow-upWhen is inheritance still the right choice?