Inheritance
MediumIn plain terms
Inheritance is a mechanism for reuse: a child class gets all the properties and methods of a parent class and can add new ones or override existing behavior. For example, "Dog" and "Cat" might extend "Animal"; they inherit eat() and sleep() but can override makeSound().
Use inheritance when there is a clear "is-a" relationship (a Dog is an Animal). The parent defines common behavior; children specialize. Overuse leads to deep, fragile hierarchies—sometimes composition (having an object of another type) is better than inheritance.
What you need to know
- •Child extends parent
- •Inherit and override
- •"Is-a" relationship
Example
Code is language-agnostic in spirit; adapt the idea to your language:
class Animal {
constructor(name) { this.name = name; }
speak() { return "Some sound"; }
}
class Dog extends Animal {
speak() { return "Woof!"; }
}
class Cat extends Animal {
speak() { return "Meow!"; }
}
const d = new Dog("Rex");
d.speak(); // "Woof!"Why this matters
Inheritance is a core OOP concept and is often discussed together with composition. Interviewers ask "when would you use inheritance vs composition?"—you need a clear answer.
How it connects
Inheritance enables polymorphism (treat different types uniformly). It relates to Liskov Substitution: subclasses must be substitutable for the base class. Overuse leads to fragile hierarchies—composition (next topic) is often preferred.
Interview focus
Be ready to explain these; they come up often.
- ▸"Is-a" relationship: Dog is an Animal; use inheritance when that holds.
- ▸super() and overriding: extend behavior while reusing parent logic.
- ▸When not to use: deep hierarchies, when "has-a" fits better (composition).
Learn more
Dive deeper with these resources: