Labs ICT
Pro Login

Inheritance

Class Inheritance with extends

The extends keyword lets a child class inherit properties and methods from a parent class.

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

  speak() {
    return this.name + " makes a sound";
  }
}

class Dog extends Animal {
  speak() {
    return this.name + " barks";
  }
}

const dog = new Dog("Rex");
console.log(dog.speak());
Try it Yourself →

The super Keyword

Call super() inside the child constructor to invoke the parent constructor. Use super.method() to call parent methods.

class Vehicle {
  constructor(brand) {
    this.brand = brand;
  }

  info() {
    return "Brand: " + this.brand;
  }
}

class Car extends Vehicle {
  constructor(brand, model) {
    super(brand);
    this.model = model;
  }

  info() {
    return super.info() + ", Model: " + this.model;
  }
}

const car = new Car("Toyota", "Corolla");
console.log(car.info());
Try it Yourself →

Method Overriding

Child classes can override parent methods by defining a method with the same name. Optionally call the parent version with super.

class Shape {
  area() {
    return 0;
  }
}

class Circle extends Shape {
  constructor(radius) {
    super();
    this.radius = radius;
  }

  area() {
    return Math.PI * this.radius * this.radius;
  }
}

const circle = new Circle(5);
console.log(circle.area().toFixed(2));
Try it Yourself →