What Is Polymorphism?

Polymorphism is one of the core principles of Object-Oriented Programming, and it builds directly on inheritance.

The idea is simple:

A child class can inherit a method from its parent class and then replace its implementation completely.

The method keeps the same name, but its behavior changes.

Example

Let’s use the same example from the previous lesson.

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() {
console.log("beeeeeep with Electric");
}
}
const eCar = new ElectricCar("Red", 2020, 50000);
console.log(eCar.color);
console.log(eCar.model);
console.log(eCar.battery);
eCar.beepSound();

What’s Different?

In the previous lesson, we wrote:

super.beepSound();
console.log("beeeeeep with Electric");

This executed the parent’s method first, then added extra behavior.

In this lesson, we removed:

super.beepSound();

and replaced the method entirely.

As a result, ElectricCar has its own implementation of beepSound() while keeping the same method name.

What Is Method Overriding?

When a child class defines a method with the same name as one in its parent class, the child’s version replaces the parent’s version.

This process is called:

Method Overriding

Method overriding is one of the most common examples of polymorphism.

Why Is Polymorphism Useful?

Polymorphism allows different objects to expose the same interface while behaving differently.

For example, every type of car may have a beepSound() method, but each type can implement it in its own way.

This makes your code more flexible, reusable, and easier to extend.

Key Takeaways

  • Polymorphism builds on inheritance.
  • A child class can override inherited methods.
  • After overriding, the child’s implementation is used instead of the parent’s.
  • Use super.methodName() if you also want to execute the parent’s implementation.
  • Polymorphism allows different objects to perform the same action in different ways.