midOOP
What is composition vs inheritance?
Updated May 17, 2026
Short answer
Composition builds objects using other objects; inheritance derives from a parent class.
Deep explanation
Composition promotes flexibility by assembling behavior, while inheritance creates rigid hierarchies.
Real-world example
Car has an engine (composition) instead of being an engine.
Common mistakes
- Overusing inheritance for code reuse.
Follow-up questions
- Why is composition preferred?
- Can both be used together?