Composition vs Inheritance
What you'll learn: You'll discover the fundamental difference between "has-a" composition and "is-a" inheritance relationships, and when to choose each design approach.
The Core Distinction
Inheritance models an "is-a" relationship: a Dog is a Animal. The subclass inherits all properties and behaviors from its parent.
Composition models a "has-a" relationship: a Car has an Engine. The containing class holds references to other objects and delegates work to them.
When to Use Inheritance
Use inheritance when there's a genuine specialization relationship:
- A
SavingsAccounttruly is aBankAccount - Subclasses share core behavior with their parent
- You need polymorphism—treating different subclasses through a common interface
When to Use Composition
Prefer composition when:
- You need functionality from another class but aren't specializing it
- The relationship is "uses" or "contains" rather than "is"
- You want more flexibility to change components at runtime
- You're combining behaviors from multiple sources (avoiding multiple inheritance complexity)
The Analogy
Think of inheritance like biological taxonomy: a Golden Retriever is a Dog is a Mammal. This hierarchy is rigid and fixed.
Composition is like building with LEGO blocks: your car has wheels, has an engine, has seats. You can swap out different engines without changing what a car fundamentally is.
Design Guideline
The famous principle "favor composition over inheritance" doesn't mean never use inheritance—it means don't default to inheritance just for code reuse. If you're inheriting primarily to get access to methods rather than to model a true specialization, composition is usually cleaner and more maintainable.
Key Takeaway: Inheritance creates "is-a" relationships for true specialization; composition creates "has-a" relationships for flexible, modular design—prefer composition unless you genuinely need polymorphic substitution.