Method Overriding in TypeScript

  • Method Overriding is a concept of Inheritance in Classes where a child class can override a function of a parent class. In this, child class may or may not use the logic of a function defined in parent class.
  • We use super keyword to refer to the functions or fields of the immediate parent class.

Below is an example of method overriding USING super. If we use super, the same method of parent class is executed.

class ParentClass { 
    display():void {
       console.log("Display method from Parent Class!") 
    } 
 } 
 
 class ChildClass extends ParentClass { 
    display():void { 
       super.display() 
       console.log("dislay method from Child Class!")
    } 
    hello():void{
        console.log("Hello from Child Class!");
    }
 } 
 
 var parentObj = new ParentClass();
 parentObj.display();
 var childObj = new ChildClass();
 childObj.display();
 childObj.hello();

Below is the output of above code

Below is an example WITHOUT using super. If we skip super, then that method of parent class is not executed. Only the method of child class is executed.

class ParentClass { 
    display():void {
       console.log("Display method from Parent Class!") 
    } 
 } 
 
 class ChildClass extends ParentClass { 
    display():void { 
       //super.display() 
       console.log("dislay method from Child Class!")
    } 
    hello():void{
        console.log("Hello from Child Class!");
    }
 } 
 
 var parentObj = new ParentClass();
 parentObj.display();
 var childObj = new ChildClass();
 childObj.display();
 childObj.hello();

Below is the output of above code

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started