Inheritance

Inheritance allows us to create new classes based on existing classes.

Consider the following example (taken from ES6 — classes and inheritance):

Reminder of OOP Class Syntax

class Vehicle {

    constructor (name, type) {
        this.name = name;
        this.type = type;
    }

    getName () {
        return this.name;
    }

    getType () {
        return this.type;
    }
}

let car = new Vehicle('Tesla', 'car');
console.log(car.getName()); // Tesla
console.log(car.getType()); // car

Inheritance Example

We use extends to inherit from another class and the super keyword to call the parent class. Moreover, getName() method was overridden in subclass Car.

class Vehicle {

    constructor (name, type) {
        this.name = name;
        this.type = type;
    }

    getName () {
        return this.name;
    }

    getType () {
        return this.type;
    }
}

class Car extends Vehicle {

    constructor (name) {
        super(name, 'car');
    }

    getName () {
        return 'It is a car: ' + super.getName();
    }
}

let car = new Car('Tesla');
console.log(car.getName()); // It is a car: Tesla
console.log(car.getType()); // car

Tutorial Video

Daniel Shiffman does an excellent job of explaining this idea using p5js. Check out his tutorial video here

Next Section - Pair Programming with OOP (Object Oriented Programming)