Skip to content
Related Articles

Related Articles

Polymorphism in JavaScript

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 09 May, 2022

What is Polymorphism?

Polymorphism is one of the core concepts of object-oriented programming language. Polymorphism means the same function with different signatures is called many times. In real life, Like a Boy at the same time is a Student, Class Monitor, etc. So Boy can perform different operations at the same time is called polymorphism.

Features of Polymorphism:

  1. Programmers can be used same method name repeatedly.
  2. Polymorphism has the effect of reducing the number of functionalities that can be paired together.

Inheritance Polymorphism in JavaScript: In this example, we will create three functions with the same name and different operations. This Program shows JavaScript Inheritance polymorphism.

Javascript




<script>
    class firstClass {
        add() {
            console.log("First Method")
        }
    }
    class secondClass extends firstClass {
        add() {
            console.log(30 + 40);
        }
    }
    class thirdClass extends secondClass {
        add() {
            console.log("Last Method")
        }
    }
    var ob = new firstClass();
    var ob2 = new secondClass();
    var ob3 = new thirdClass();
    ob.add();
    ob2.add();
    ob3.add();
</script>


Output:

First Method
70
Last Method

The Code above shows how to implement inheritance polymorphism in JavaScript. In this code, we have a class and in this class, we have the “add” method and we Inherit this class in the Second Class. We create different classes with the same method name and different definitions of methods. This example shows us same method will be performed in different operations.

Polymorphism with Functions and Objects: It is also possible in JavaScript that we can make functions and objects with polymorphism. In the next example, we will make two functions with the same name ‘area’. In class A, we define the area function. In this function, we have two parameters. In ‘class B ‘ extends ‘class A’, In area function call ‘class A ‘ function by super keyword and we make object of ‘class b’ and call area function by object and passing values to area function.

Implementing Polymorphism with Functions and Object.

Javascript




<script>
    class A {
        area(x, y) {
            console.log(x * y);
        }
    }
    class B extends A {
        area(a, b) {
            super.area(a, b);
        }
    }
    var ob = new B();
    var output = ob.area(100, 200);
</script>


Output:

20000

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!