How to Use Super Classes in JavaScript?

Estimated read time 2 min read

In JavaScript, classes can be used to create objects with similar properties and methods. Classes can also inherit properties and methods from other classes through the use of superclasses. A superclass is simply a class that is the parent of another class. The child class, also known as the subclass, inherits all the properties and methods of the superclass.

Here is an example of how to create a superclass and a subclass in JavaScript:

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

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

const dog = new Dog('Rufus');
dog.speak();
// Output: Rufus barks.

In this example, the Animal class is the superclass and the Dog class is the subclass. The Dog class extends the Animal class, which means that it inherits all the properties and methods of the Animal class. In this case, the Dog class has a speak method that overrides the speak method of the Animal class.

The super keyword can be used in the subclass to access the properties and methods of the superclass. Here’s an example:

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

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

const dog = new Dog('Rufus');
dog.speak();
// Output: Rufus makes a sound.
//         Rufus barks.

In this example, the Dog class’s speak method uses super.speak() to access the speak method of the Animal class. This allows the Dog class to both call the speak method of the Animal class and add its own behavior.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply