Inheritance
Child classes acquire their parent's properties and methods — specialize and extend rather than duplicate.
Intent & Description
🎯 Intent
Classes that share common structure shouldn’t duplicate it — one base class holds shared state and behavior; child classes specialize it.
📋 Context
Dog, Cat, and Bird all have a name, can speak, and can eat. Without inheritance, you copy those fields and methods three times and maintain them in sync forever. Each variant is a copy waiting to diverge.
💡 Solution
Define an Animal base class with the shared properties and methods. Dog, Cat, and Bird extend Animal — they inherit name and base behavior for free, then override or add what makes each one distinct.
Real-world Use Case
📌 TL;DR
Share and specialize. Inheritance is a strong coupling — if “is-a” doesn’t genuinely hold, reach for composition instead.
Advantages
- Eliminates code duplication across related classes
- Establishes a readable, logical hierarchy
- Child classes inherit and specialize without rewriting shared logic
Disadvantages
- Creates tight coupling — changes to the base class cascade down every child
- Deep hierarchies become brittle and hard to reason about
- Often misused for code reuse without a genuine “is-a” relationship — composition is usually the right fix
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks`;
}
}
class Cat extends Animal {
speak() {
return `${this.name} meows`;
}
}
const dog = new Dog('Rex');
const cat = new Cat('Whiskers');
console.log(dog.speak()); // "Rex barks"
console.log(cat.speak()); // "Whiskers meows"