Inheritance: Unlocking Code Reusability in JavaScript

Introduction to Inheritance

Greetings, coder! Our voyage into Object-Oriented Programming (OOP) continues. Today, we will cover Inheritance, which can make our code more efficient and tidy.

Inheritance: First Example

Just as children inherit traits from their parents, child classes in programming inherit behaviors and properties from parent classes.

Below is a practical example displaying a child class inheriting from a parent class:

JavaScript
// Parent class
class Parent {
    constructor(name) {
        this.name = name; // name property
    }

    greet() {
        console.log(`Hello, my name is ${this.name}`); // greet method
    }
}

// 'Child' class extending 'Parent'
class Child extends Parent {
    constructor(name, age) {
        super(name); // call to parent constructor of `Parent`
        this.age = age; // age property
    }

    info() {
        console.log(`I am ${this.age} years old.`); // info method
    }
}

const child = new Child('Alice', 10);
child.greet(); // prints: Hello, my name is Alice
child.info(); // prints: I am 10 years old.

In this example, Child inherits from Parent, so it shares the greet() method, making our code smarter!

Understanding the 'extends' Keyword

To implement inheritance, we introduce a keyword: 'extends'. This powerful keyword allows a new class to inherit properties and methods from an existing class. Let's say, a 'child' class 'extends' from the 'parent' class.

Let's see how a car can extend a vehicle. Both are entities with the potential for motion, but a car offers additional specific features — such as wheels.

JavaScript
// Vehicle class
class Vehicle {
    constructor(name, speed) {
        this.name = name; // name property
        this.speed = speed; // speed property
    }
    move() {
        console.log(`${this.name} moves at ${this.speed} mph.`); // move method 
    }
}

// 'Car' class extending 'Vehicle'
class Car extends Vehicle {
    constructor(name, speed, wheels) {
        super(name, speed); // call to parent constructor
        this.wheels = wheels; // new wheels property
    }
    specs() {
        console.log(`I am a ${this.name} and I have ${this.wheels} wheels.`); // specs method
    }
}

const myCar = new Car('Toyota', 120, 4);
myCar.move(); // prints: Toyota moves at 120 mph
myCar.specs(); // prints: I am a Toyota and I have 4 wheels.

In this code, the Car class extends from the Vehicle class, sharing the move() method.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal