What Is Inheritance?

Inheritance is one of the core principles of Object-Oriented Programming.

The idea is simple: instead of rewriting the same properties and methods in multiple classes, you create a new class that inherits them from an existing one, then add only what makes it unique.

This reduces code duplication and promotes code reuse.

Example

Suppose we already have a Car class.

class Car {
constructor(color, model) {
this.color = color;
this.model = model;
}
beepSound() {
console.log("beeeeeeeeeep");
}
}
class ElectricCar extends Car {
constructor(color, model, battery) {
super(color, model);
this.battery = battery;
}
}
const eCar = new ElectricCar("Red", 2020, 50000);
console.log(eCar.color);
console.log(eCar.model);
console.log(eCar.battery);
eCar.beepSound();

What Happened?

We created a new class called ElectricCar.

Instead of redefining all the properties and methods from Car, we used the keyword:

extends

This tells JavaScript that ElectricCar inherits everything from Car.

As a result, the new class automatically gains access to:

  • color
  • model
  • beepSound()

without redefining them.

What Does super() Do?

Inside the constructor, you’ll notice:

super(color, model);

super() calls the parent class constructor, allowing it to initialize the inherited properties.

After that, we add a new property specific to electric cars:

this.battery = battery;

Now every ElectricCar object contains both the inherited data and its own battery information.

Overriding Methods

Sometimes you want to extend a method instead of replacing it completely.

You can override the inherited method and still call the original implementation.

class Car {
constructor(color, model) {
this.color = color;
this.model = model;
}
beepSound() {
console.log("beeeeeeeeeep");
}
}
class ElectricCar extends Car {
constructor(color, model, battery) {
super(color, model);
this.battery = battery;
}
beepSound() {
super.beepSound();
console.log("beeeeeep with Electric");
}
}

Why Use super Again?

Inside the overridden method:

super.beepSound();

we first execute the parent’s version of the method.

After that, we add additional behavior that’s specific to ElectricCar.

This allows us to reuse the original implementation while extending it with new functionality.

Key Takeaways

  • Inheritance allows one class to reuse another class’s properties and methods.
  • Use the extends keyword to inherit from another class.
  • Use super() to call the parent constructor.
  • Use super.methodName() to execute a parent method.
  • Inheritance reduces code duplication and encourages code reuse.