Skip to main content

Archive

Show more

JavaScript Class Inheritance

JavaScript Class Inheritance

Class inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and methods from another class. In JavaScript, this is achieved using the extends keyword, which enables one class (the subclass) to inherit from another class (the superclass). This concept promotes code reuse and helps organize complex systems by breaking them into hierarchical relationships.


1. Basic Class Inheritance in JavaScript

In JavaScript, when one class inherits from another, the subclass gains access to the properties and methods of the superclass. The super() function is used within the subclass to call the constructor of the superclass.

Example of Class Inheritance

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

  // Method in the parent class
  speak() {
    return `${this.name} makes a sound.`;
  }
}

// Subclass inheriting from Animal
class Dog extends Animal {
  constructor(name, breed) {
    // Call the parent class constructor using super()
    super(name);
    this.breed = breed;
  }

  // Overriding the speak() method
  speak() {
    return `${this.name}, the ${this.breed}, barks.`;
  }
}

// Creating an instance of the subclass
const dog = new Dog("Rex", "German Shepherd");
console.log(dog.speak());  // Output: Rex, the German Shepherd, barks.

In this example, the Dog class extends the Animal class, inheriting the name property and the speak() method. The speak() method is overridden in the Dog class to provide a specific behavior for dogs.


2. The super() Keyword

The super() keyword is used to call the constructor of the superclass within the subclass. This is necessary when the subclass needs to pass arguments to the parent class constructor, as demonstrated in the previous example.

Using super() in Class Inheritance

class Vehicle {
  constructor(type, speed) {
    this.type = type;
    this.speed = speed;
  }

  move() {
    return `${this.type} moves at ${this.speed} km/h.`;
  }
}

class Car extends Vehicle {
  constructor(type, speed, brand) {
    // Call the parent class constructor
    super(type, speed);
    this.brand = brand;
  }

  details() {
    return `The ${this.brand} ${this.type} moves at ${this.speed} km/h.`;
  }
}

const car = new Car("Sedan", 120, "Toyota");
console.log(car.details());  // Output: The Toyota Sedan moves at 120 km/h.

In this example, the Car class uses the super() keyword to call the constructor of the Vehicle class, allowing it to inherit the type and speed properties.


3. Overriding Methods

In JavaScript, a subclass can override methods of the superclass by defining methods with the same name in the subclass. This is useful when you want to provide a specialized implementation of a method for the subclass.

Overriding a Method in a Subclass

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

  fly() {
    return `${this.name} flies high.`;
  }
}

class Penguin extends Bird {
  // Overriding the fly method
  fly() {
    return `${this.name} cannot fly, but swims instead.`;
  }
}

const penguin = new Penguin("Pablo");
console.log(penguin.fly());  // Output: Pablo cannot fly, but swims instead.

In this example, the Penguin class overrides the fly() method inherited from the Bird class, providing a specific behavior for penguins.


4. Inheriting Static Methods

Static methods in a superclass are also inherited by subclasses. Static methods are called on the class itself rather than on instances of the class. The subclass can call the inherited static methods, or it can override them as needed.

Inheriting Static Methods Example

class Calculator {
  static add(a, b) {
    return a + b;
  }
}

class AdvancedCalculator extends Calculator {
  static subtract(a, b) {
    return a - b;
  }
}

console.log(AdvancedCalculator.add(5, 3));  // Output: 8
console.log(AdvancedCalculator.subtract(5, 3));  // Output: 2

In this example, the AdvancedCalculator class inherits the static add() method from the Calculator class and adds its own static subtract() method.


5. Class Inheritance with Getters and Setters

Getters and setters can also be inherited by subclasses. They allow controlled access to properties in both the superclass and the subclass.

Using Getters and Setters in Inheritance

class Shape {
  constructor(name) {
    this._name = name;
  }

  get name() {
    return this._name;
  }

  set name(newName) {
    this._name = newName;
  }
}

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

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

const circle = new Circle("My Circle", 10);
console.log(circle.name);  // Output: My Circle
console.log(circle.area);  // Output: 314.159...

In this example, the Circle class inherits the name getter and setter from the Shape class. It also introduces a new getter, area, to calculate the area of the circle.


Conclusion

Class inheritance in JavaScript allows for better code reuse and organization by enabling classes to share properties and methods. By leveraging the extends keyword, subclasses can inherit and extend the functionality of superclasses, override methods, and define their own behavior. This feature is a key part of object-oriented programming in JavaScript and is essential for writing scalable and maintainable code.

Comments