JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Class Inheritance

14 April 2025 | Category:

Inheritance is a fundamental concept in object-oriented programming (OOP), and JavaScript supports it through classes and the extends keyword.

It allows a child class to inherit properties and methods from a parent class, enabling code reuse and a cleaner structure.


📚 Why Use Inheritance?

Imagine you have several objects that share some common behavior. Instead of repeating code, you define the shared logic in a base class, then extend it in other classes that add or override specific functionality.


đŸ§± Basic Example

đŸ§© Parent Class

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

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

🔗 Child Class

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

✅ Usage

const dog = new Dog("Rex");
dog.speak(); // Output: Rex barks.

Dog inherits from Animal and overrides the speak() method.


🧠 Using super()

The super() function is used to call the constructor or methods of the parent class.

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

  start() {
    console.log(`Starting the ${this.type}`);
  }
}

class Car extends Vehicle {
  constructor(type, brand) {
    super(type); // calls Vehicle's constructor
    this.brand = brand;
  }

  start() {
    super.start(); // calls Vehicle's start method
    console.log(`${this.brand} is now running.`);
  }
}

const myCar = new Car("Car", "Toyota");
myCar.start();
// Output:
// Starting the Car
// Toyota is now running.

🔄 Method Overriding

You can override a method from the parent class by redefining it in the child class. This allows for specific behavior.

class Bird extends Animal {
  speak() {
    console.log(`${this.name} sings.`);
  }
}

const sparrow = new Bird("Sparrow");
sparrow.speak(); // Sparrow sings.

đŸ§Ș Inheriting Without Overriding

If a child class doesn’t override a method, it will automatically use the parent’s version.

class Cat extends Animal {}

const kitty = new Cat("Milo");
kitty.speak(); // Milo makes a sound.

🔐 Inheritance Summary Table

ConceptDescription
extendsAllows one class to inherit from another
super()Calls parent class constructor or method
Method OverridingChild class can define its own version of a method
Code ReusabilityShared logic stays in the parent class

🚀 Benefits of Class Inheritance

  • Reduces code duplication
  • Improves maintainability
  • Makes your code more scalable
  • Promotes cleaner architecture