Polymorphism in JavaScript
In this tutorial, we will learn about polymorphism in JavaScript.
Polymorphism is one of the four fundamental OOP concepts. It is the ability of an object to take on many forms. It allows objects of different classes to be treated as objects of a common superclass. It allows a single interface to be used for objects of different classes.
JavaScript supports polymorphism through method overriding. Method overriding is the ability of a subclass to provide a specific implementation of a method that is already provided by its superclass. It allows a subclass to provide a specific implementation of a method that is already provided by its superclass.
Example
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`);
}
}
class Cat extends Animal {
speak() {
console.log(`${this.name} meows`);
}
}
let dog = new Dog("Buddy");
let cat = new Cat("Kitty");
dog.speak(); // Buddy barks
cat.speak(); // Kitty meowsIn the above example, the Animal class is the base class, and the Dog and Cat classes are the derived classes. The Dog and Cat classes override the speak method of the Animal class to provide a specific implementation.
Conclusion
- Polymorphism is the ability of an object to take on many forms.
- JavaScript supports polymorphism through method overriding.
- Method overriding is the ability of a subclass to provide a specific implementation of a method that is already provided by its superclass.
- Polymorphism allows objects of different classes to be treated as objects of a common superclass.
- Polymorphism allows a single interface to be used for objects of different classes.
- Polymorphism is used to create a relationship between classes and to provide a way to use a single interface for objects of different classes.
- Polymorphism is used to reuse code and to create a hierarchy of classes where one class is a subclass of another class.
- Polymorphism is used to provide a way to use a single interface for objects of different classes.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on