JavaScript Class Inheritance
About JavaScript Class Inheritance
In JavaScript, class inheritance allows programmers to create new classes based on existing classes.
The new class inherits properties and methods from the existing class.
New properties and methods can be added to the new class.
Parent Class: A parent class, also known as a base class or superclass, is a class that other classes inherit from.
Child Class: The class that inherits from the parent class is called the child class or derived class or subclass.
Inheriting a Class
The extends keyword is used to establish inheritance between classes (e.g. class Dog extends Animal).
The super() keyword is used to call the constructor or methods of parent class (e.g. super(name)).
Simple Example of Inheriting a Class
Explanation of The Code
-
class Animal {...}:Animalclass is defined with thenameproperty. -
class Dog extends Animal{...}: TheDogclass is defined inheriting from theAnimalclass. Theextendskeyword is used to inheritDogclass from theAnimalclass. Thesuper()keyword is used to call the constructor ofAnimalclass. HereAnimalclass is the parent class and theDogclass is the child class.this.breed = breedadds a new property to theDogclass. -
let myDog = new Dog("Buddy", "German Shepherd"): This creates a new instance ofDogclass. -
myDog.name myDog.breed: These codes access thenameandbreedproperties of the instance. The Dog class can use the name property from the parent class (Animal class) and the breed property from the child class (Dog class) as well.
Calling Parent Class Methods
Parent class method can be directly called using the child class instance (e.g. myDog.speak()).
The super() keyword is also used to call methods of the parent class inside from a method of a child class (e.g. super.speak()).
Example of Calling Parent Class Methods
Output of the above example
Charlie makes a sound.
Charlie makes a sound.
Charlie is a German Shepherd.
Explanation of The Code
-
speak(){...}: Thespeak()) is a method defined in theAnimalclass (parent class). -
describe(){...}: Thedescribe()) is a method defined in theDogclass (child class). -
myDog.speak(): This calls thespeak()method of parent class using the instance (myDog) of child class (Dog class). -
myDog.describe(): This calls thedescribe()method of Dog class.
JavaScript Compiler For Live Practice
Practice the above JavaScript code in the following JavaScript Editor. Create more classes and implement inheritance in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.
JavaScript Editor