In Javascript, Polymorphism is a concept in object-oriented programming that allows objects of different types to be treated as objects of a common base type.
It enables a single interface to represent different types of objects, providing a unified way to interact with them.
Polymorphism is often achieved through method overriding and inheritance.
Polymorphism can be demonstrated through the use of prototype-based "inheritance" and "method overriding".
// Base class (Superclass) function Vehicle(bodyType) { this.bodyType = bodyType; } // Method in the base class prototype Vehicle.prototype.makeSound = function() { console.log("Some generic sound"); }; // Subclass (Derived class) function Car(name, bodyType) { Vehicle.call(this, bodyType); this.name = name; } // Set up prototype chain Car.prototype = Object.create(Vehicle.prototype); Car.prototype.constructor = Car; // Method override in the subclass Car.prototype.makeSound = function() { console.log("Pee! Pee!"); }; // Function that takes an Vehicle and calls makeSound function performSound(vehicle) { vehicle.makeSound(); } // Creating instances const yourVehicle = new Vehicle("SUV"); const yourCar = new Car("Defender", "SUV"); // Using polymorphism with the performSound function performSound(yourVehicle); // Outputs: Some generic sound performSound(yourCar); // Outputs: Pee! Pee!
The `Vehicle` class has a makeSound method in its prototype.
The `Car` class is a subclass of `Vehicle` and overrides the makeSound method.
The performSound function takes an `Vehicle` parameter and calls the makeSound method on it.
This function demonstrates polymorphism because it can accept objects of different types (e.g., Vehicle or Car) and still call the appropriate makeSound method based on the actual type of the object.
class Vehicle { constructor(bodyType) { this.bodyType = bodyType; } makeSound() { console.log("Some generic sound"); } } class Car extends Vehicle { constructor(name, bodyType) { super(bodyType); this.name = name; } makeSound() { console.log("Pee! Pee!"); } } function performSound(vehicle) { vehicle.makeSound(); } // Creating instances const yourVehicle = new Vehicle("SUV"); const yourCar = new Car("Defender", "SUV"); // Using polymorphism with the performSound function performSound(yourVehicle); // Outputs: Some generic sound performSound(yourCar); // Outputs: Pee! Pee!
the ES6 class syntax provides a cleaner way to define classes and their methods while preserving the concept of polymorphism through method overriding.
Polymorphism allows for more flexible and extensible code by enabling the use of common interfaces and behaviors across different types of objects.
It's a key aspect of object-oriented programming that promotes code reuse and maintainability.