is-a vs has-a: Composition vs Inheritance
You'll learn how to choose between inheritance (is-a) and composition (has-a) to model relationships correctly.
The Two Fundamental Relationships
When designing classes, you have two main ways to create relationships:
- is-a (Inheritance): A subclass is a specialized version of its superclass
- has-a (Composition): A class has a field that references another object
Understanding is-a
You use inheritance when one class is a type of another. A Dog is an Animal, so inheritance makes sense. This creates a direct lineage and enables polymorphism.
class Animal {
void breathe() { }
}
class Dog extends Animal { // Dog IS-A Animal
void bark() { }
}
Understanding has-a
You use composition when one class contains another as a component. A Car isn't a type of Engine, but it has an engine.
class Engine {
void start() { }
}
class Car { // Car HAS-A Engine
private Engine engine;
public Car() {
this.engine = new Engine();
}
}
Making the Right Choice
Ask yourself: "Does X need to be treated as a Y?" or "Does X merely use Y as a part?"
- A
Professoris aPerson→ use inheritance - A
Professorhas aCoursethey teach → use composition
Composition is often more flexible because it doesn't lock you into a rigid hierarchy. You can swap out components and combine multiple objects easily.
Key Takeaway: Use inheritance (extends) when modeling "is-a" type relationships; use composition (fields) when modeling "has-a" ownership or usage relationships. When in doubt, favor composition for flexibility.