Javascript class inheritance

Extending a Class

Inheritance is a mechanism by a witch one object acquires all the properties and behaviours of a parent object. But to understand the concept of class you need to understand the concept of Class. Mainly we will use this term when we are using Inheritance.

1. Sub Class or Child Class: Class which inherits the other class.
2. Super Class or Parent Class: Class from where a subclass inherits the features.

extends keyword play an important role to inherit the properties of parent class.


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

    getName() {
        return this.name;
    }
}

class BE extends Student {
    constructor(name, clg) {
        super(name);
        this.clg = clg;
    }

    getClg() {
        return this.clg;
    }
}

var stu = new BE("xyz", "abc");
stu.getName(); // xyz
stu.getClg(); // abc

Method Overriding in JavaScript

In a method, overriding parent class and child class have same method name and child class override parent class method. You can see in bellow example run class override by bike class.


class Vehicle {
    run() {
        console.log("My vehicle is running.");
    }
}

class Bike extends Vehicle{  
    run() {
        console.log("My bike is running.");
    }
}

var bike = new Bike();
bike.run(); // My bike is running.

Shadowing Class Methods

But what will happen when you need a parent class method. In below example you can see we need to modify the parent class method, in that case, we can use this technique.


class Rectangle {
    constructor(length, width) {
        this.length = length;
        this.width = width;
    }

    getArea() {
        return this.length * this.width;
    }
}

class Square extends Rectangle {
    constructor(length) {
        super(length, length);
    }

    getArea() {
        return `Square is:: ${super.getArea()}`;
    }
}

var square = new Square(3);
square.getArea(); // Square is:: 9

Super keyword

Super is spacial keyword which is used to refer immediate parent class object. In the previous example, you can see we have used super with a constructor and inside a method. In Square class, first of all, we pass length to Rectangle class constructor then inside getArea we are using Rectangle class getArea method

You May Also Like

About the Author: Pankaj Bisht