Q19: What is Composition versus Inheritance, and why favor Composition?
- Inheritance (
IS-A): Tightly couples subclass to superclass implementation details (class Dog extends Animal). Modifying parent behavior risks breaking derived subclasses. - Composition (
HAS-A): Assembles complex objects by embedding component objects as private fields (class Car { private Engine engine; }). - Principle: Favor Composition over Inheritance to achieve loose coupling, runtime behavior swapping, and robust encapsulation.
Key Takeaways
- Inheritance =
IS-Arelationship (tight coupling). Composition =HAS-Arelationship (loose coupling, runtime flexibility).
Knowledge Check
Which design principle helps avoid brittle class hierarchies when extending framework features?