# Inheritance

> Child classes acquire their parent's properties and methods — specialize and extend rather than duplicate.

- **Category**: Oop Concepts
- **Subcategory**: relationships
- **Canonical URL**: https://designpattern.fyi/oop-concepts/inheritance/

---

## 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.



## Use Cases
A genuine "is-a" relationship exists between classes (Dog is an Animal; Square is not a Rectangle). Multiple classes share real common structure, not just coincidental similarity. You're building a taxonomy where specialization is the organizing idea.



## Implementation Example

```javascript
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"
```



## Trade-offs


### Advantages

- Eliminates code duplication across related classes

- Establishes a readable, logical hierarchy

- Child classes inherit and specialize without rewriting shared logic




### Considerations & Drawbacks

- 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







