javascript
  1. javascript-polymorphism

JavaScript Polymorphism

Syntax

//Parent Class
class Vehicle {
  constructor(name, manufacturer) {
    this.name = name;
    this.manufacturer = manufacturer;
  }

  start() {
    console.log('Starting Engine...');
  }
}

//Child Class
class Car extends Vehicle {
  constructor(name, manufacturer, doors) {
    super(name, manufacturer);
    this.doors = doors;
  }

  start() {
    console.log('Starting Car Engine...');
  }
}

Example

const vehicle = new Vehicle('SUV', 'Ford');
vehicle.start(); // Starting Engine...

const car = new Car('Mustang', 'Ford', 2);
car.start(); // Starting Car Engine...

Output

Starting Engine...
Starting Car Engine...

Explanation

Polymorphism is the ability of an object to take on many forms. In JavaScript, we can achieve polymorphism through Method Overriding, where the child class method can override the parent class method.

In the given example, we have defined two classes - Vehicle and Car. Car is a child class of Vehicle. The start method is defined in both classes, but the implementation of the start method is different in both classes. When we create an object of the Car class and call the start method, it will execute the implementation of the start method present in the Car class.

Use

Polymorphism is used in JavaScript to create objects with various forms and behaviors through method overriding. It reduces the code redundancy and increases code reusability.

Important Points

  • Polymorphism is the ability of an object to take on many forms.
  • JavaScript achieves polymorphism through Method Overriding.
  • The child class method can override the parent class method.
  • Polymorphism reduces code redundancy and increases code reusability.

Summary

In JavaScript, Polymorphism is the ability of an object to take on many forms through Method Overriding. Polymorphism reduces code redundancy and increases code reusability. We can achieve Polymorphism in JavaScript by defining a parent class and one or more child classes that share the same properties and methods. The child class can override the parent class method through method overriding.

Published on: