H.dev

Inheritance

What is Inheritance?

Inheritance is an OOP concept where one class can inherit (or borrow) all the properties and methods from another class. This allows you to write reusable code and establish a parent-child relationship between classes.

For example, Dog and Cat are both types of an Animal. Instead of writing eating and sleeping methods twice, you can write them once in an Animal class, and let Dog and Cat inherit them.

The 'extends' and 'super' Keywords

In JavaScript, we use the extends keyword to make a child class inherit from a parent class.

If the child class has its own constructor(), it must call super() before using the this keyword. super() calls the constructor of the parent class.

// Parent Class
class Animal {
    constructor(name) {
        this.name = name;
    }

    eat() {
        console.log(`${this.name} is eating.`);
    }
}

// Child Class
class Dog extends Animal {
    constructor(name, breed) {
        super(name); // Calls the Animal constructor to set the name
        this.breed = breed;
    }

    bark() {
        console.log(`${this.name} says Woof!`);
    }
}

const myDog = new Dog("Buddy", "Golden Retriever");
myDog.eat();  // Output: "Buddy is eating." (Inherited from Animal)
myDog.bark(); // Output: "Buddy says Woof!" (Specific to Dog)

Method Overriding

A child class can also "override" a method from its parent. If both classes have a method with the same name, the child's method will take priority.

class Bird extends Animal {
    // Overriding the eat method
    eat() {
        console.log(`${this.name} pecks at the seeds.`);
    }
}

const myBird = new Bird("Tweety");
myBird.eat(); // Output: "Tweety pecks at the seeds."

💡 Himanshu's Tip:

Inheritance is powerful, but don't overuse it! In modern JavaScript (especially in frameworks like React), developers often prefer Composition over Inheritance. Instead of deeply nested parent-child classes, it is often better to compose smaller, independent functions or components together.

Interview Questions

  1. What does the extends keyword do in JavaScript?
  2. Why must you call super() in a child class constructor?
  3. What is method overriding?

Design & Developed by Himanshu Dubey © 2026