techStackGuru

JavaScript Class Inheritance


Inheritance allows you to create a class that inherits all of the functionality of a parent class while also allowing you to add new features. A class can inherit all of the methods and attributes of another class via class inheritance. Inheritance is a valuable feature for reusing code.


Advantages of Inheritance

  • The most significant benefit of inheritance is that it facilitates code reuse.
  • Easy to debug.
  • It increases the readability of the program structure.

We use extends keyword for class inheritance. Lets take an example of inheritance


// Parent class
class Bark { 
    constructor(sound) {
        this.sound = sound;
    }

    play() {
        console.log(this.sound); 
    }
}

// Inheriting parent class
class Animal extends Bark {

}

let makeSound = new Animal('hee-haw');
makeSound.play();
Output

hee-haw

The Animal class inherits all of the methods and attributes of the Bark class in the example above. As a result, the Animal class now has a sound property as well as a play() function.

Lets take another example of Date object in inheritance


class ShowDate extends Date {  
    constructor() {  
      super();  
}}  

var object=new ShowDate();  
  
console.log(object.getDate())
console.log(object.getMonth()+1)
console.log(object.getFullYear())
Output

16
3
2022

previous-button
next-button