JavaScript Inheritance

Inheritance is a method through which the objects inherit the properties and the methods from the other objects. With the use of this, we can reuse the code and structuring of the relationship between the objects and we can create the hierarchy where a child object can access the properties and features of parent objects.
In simple words, we use inheritance for passing down the characteristics from parent to child so that new code can be reused and built upon the features of an existing one.
JavaScript inheritance is a mechanism that allows us to create new classes based on already existing classes. It allows the child class to reuse the methods and variables of a parent class.
The JavaScript extends keyword is used to create a child class based on a parent class. It facilitates the child class to acquire all the properties and behavior of its parent class.

Inheritance Syntax


class ParentClass {
    constructor(name) {
        this.name = name;
    }

    greet() {
        return `Hello, my name is ${this.name}`;
    }              
}
            
class ChildClass extends ParentClass {
    constructor(name, age) {
        super(name); // Call parent constructor
        this.age = age;
    }
            
    introduce() {
        return `${this.greet()} and I am ${this.age} years old.`;
        }
}

Key Features of Inheritance:

Example: Implementing Inheritance

Example


class Animal {
    constructor(name) {
        this.name = name;
    }
            
    speak() {
    return `${this.name} makes a noise.`;
   }
}
            
class Dog extends Animal {
    constructor(name, breed) {
        super(name); // Call parent constructor
        this.breed = breed;
    }
            
        speak() {
        return `${this.name} barks.`;
    }
}
            
// Using the classes
const genericAnimal = new Animal("GenericAnimal");
console.log(genericAnimal.speak()); // Output: GenericAnimal makes a noise.
            
const myDog = new Dog("Buddy", "Golden Retriever");
console.log(myDog.speak()); // Output: Buddy barks.
            

Output

GenericAnimal makes a noise.
Buddy barks.

Explanation of Code:

Uses of Inheritance

We use a child class can inherit all the properties and functionalities of the parents class which allows us to reuse the code. When a functionality is developed we can simply inherit the properties. We don't need to reinvent the wheel. It allows us to clear the code and it can be easier to maintain. We can add our functionalities in the child class, which can help us to inherit the only necessary properties and methods that define the required features. With the use of inheritance, we can organize the data in a hierarchal form. By using inheritance, we can make the code debugging friendly.