JavaScript Polymorphism

Javascript polymorphism allows us to override the parent class method in the subclass as per our requirement.

Example

In this example, the child class object invokes the parent class method.

Source Code

          
            class Person {
  displayMessage() {
    document.writeln("Person class displayMessage() is invoked");
  }
}
class Student extends Person {}
var s = new Student();
s.displayMessage();          
        
Try it now

Example 2

Let's see an example where a child and parent class contains the same method. Here, the object of child class invokes both classes methods.

Source Code

          
            class Person{  
displayMessage(){  
  document.writeln("Hello,have you understood polymorphism?");
 }  
}  
class Student extends Person  
  {  
displayMessage(){  
      document.write("I have learned polymorphism successfully.");
  }  
}    
let p = new Person();
let s = new Student();
p.displayMessage();
s.displayMessage();          
        
Try it now

Web Tutorials

Javascript Polymorphism
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4