In this JavaScript lesson we are going to talk about JavaScript Class Inheritance, also we will learn that how you can use method overriding in JavaScript, so class inheritance is the mechanism of basing an object or class upon another object or class, retaining similar implementation. Also defined as deriving new classes from existing ones such as super class or base class and then forming them into a hierarchy of classes.
Now let’s create an example of class inheritance. in this code we have two classes the first one is our Animal class and it is our base class, we have another Dog class that extends from the Animal base class, if you see the Animal class we have a function of speak(). now our Dog class after extending from the Animal class can access to this function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Animal { constructor(name) { this.name = name } speak() { console.log(`${this.name} make noise`); } } class Dog extends Animal { constructor(name) { super(name) } } let dog = new Dog("Dog"); dog.speak(); |
Also you can do method overriding, for example if you want to change the functionality of the speak() function in your extended class than you can use method overriding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class Animal { constructor(name) { this.name = name } speak() { console.log(`${this.name} make noise`); } } class Dog extends Animal { constructor(name) { super(name) } speak() { console.log(`${this.name} barking`); } } let dog = new Dog("Dog"); dog.speak(); |