← All Quizzes
Why is composition often preferred over inheritance?
Explanation
Composition over inheritance is a principle favoring object composition over class inheritance for code reuse. Benefits of composition: flexibility (behavior can be added/changed at runtime), avoids fragile base class problem, no deep hierarchy issues, better encapsulation, and easier testing. Inheritance creates tight coupling (subclass depends on parent implementation) and is static (compile-time). Composition uses interfaces/traits/mixins to combine behavior, following SOLID principles. Use inheritance for true 'is-a' relationships (rare) and composition for 'has-a' or 'can-do' relationships (common).