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 {...}: Animal class is defined with the name property.
  • class Dog extends Animal{...}: The Dog class is defined inheriting from the Animal class. The extends keyword is used to inherit Dog class from the Animal class. The super() keyword is used to call the constructor of Animal class. Here Animal class is the parent class and the Dog class is the child class. this.breed = breed adds a new property to the Dog class.
  • let myDog = new Dog("Buddy", "German Shepherd"): This creates a new instance of Dog class.
  • myDog.name myDog.breed: These codes access the name and breed properties 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(){...}: The speak()) is a method defined in the Animal class (parent class).
  • describe(){...}: The describe()) is a method defined in the Dog class (child class).
  • myDog.speak(): This calls the speak() method of parent class using the instance (myDog) of child class (Dog class).
  • myDog.describe(): This calls the describe() 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 logo JavaScript Editor
JavaScript Code Output