Inheritance & extends

In JavaScript, class inheritance allows a class to acquire properties and methods from another class. This promotes code reuse and logical hierarchy.

Illustration of inheritance_extends
Illustration of inheritance_extends

💡 What is Inheritance?

Inheritance lets a new class (called child or subclass) adopt the features of an existing class (called parent or superclass).

The keyword extends is used to create a subclass that inherits from a parent class.

Basic Syntax
Parent ClassChild Class
class Animal { ... } class Dog extends Animal { ... }

When a child class extends a parent, it automatically gets all its methods and properties. The child can also add or override methods.

📌 Deep Dive: Simple Inheritance

JAVASCRIPT
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a noise.`;
  }
}

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

const dog = new Dog("Buddy");
console.log(dog.speak()); // Buddy barks.
Output
Buddy barks.

In this example:

  • Dog inherits Animal's constructor and speak method.
  • The Dog class overrides speak to provide its own behavior.

💡 Using super

Inside a subclass, super calls the parent class's constructor or methods.

📌 Deep Dive: Calling super

JAVASCRIPT
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a noise.`;
  }
}

class Cat extends Animal {
  constructor(name, color) {
    super(name); // Calls Animal constructor
    this.color = color;
  }
  speak() {
    return super.speak() + ` It is a ${this.color} cat.`; // Calls Animal speak
  }
}

const cat = new Cat("Whiskers", "black");
console.log(cat.speak()); // Whiskers makes a noise. It is a black cat.
Output
Whiskers makes a noise. It is a black cat.

⚠️ Important

In subclass constructors, super() must be called before using this. Omitting it will cause a ReferenceError.

Summary: Inheritance with extends
FeatureDescription
extendsDefines a subclass that inherits from a parent class.
InheritanceSubclass gets parent's methods and properties automatically.
OverridingSubclass can redefine parent's methods to change behavior.
super()Used in constructor to call parent class constructor.
super.method()Calls parent class method from subclass.

💡 Why Use Inheritance?

Inheritance helps organize code by creating a clear relationship between general and specialized classes, avoiding repetition and enhancing maintainability.