Open In App

Method Overriding in TypeScript

In this article, we will understand some of the necessary details which are associated with Method Overriding, further, we will see how to implement Method Overriding in TypeScript.

Method Overriding:



After analyzing all the basic facts associated with the Method Overriding in TypeScript, let us now see how we could implement Method Overriding in TypeScript with some of the following illustrated examples.

Example 1: In this example, we will declare two classes and inside the parent class we will declare one method which will be overridden by the child class with its own logic.






class Boy {
    name : string
    about() : void {
        console.log(this.name +" is an intelligent boy..")
    }
}
   
class Student extends Boy {
    rollnumber : number;
    marks: number;
    constructor(rollnumber : number, marks : number, 
    name1 : string){
        super(); 
        this.rollnumber = rollnumber
        this.name = name1
        this.marks = marks
    }
    displayStudentInformation() : void {
        console.log("Name : "+ this.name +", Roll Number : "
        this.rollnumber +", 
        Scores : " + this.marks + " out of 100" )
    }
    about() : void{
        console.log(this.name + " scores well...")
    }
  
let student = new Student(2, 96, "Rohit");
student.displayStudentInformation();
student.about();

Output:

Name : Rohit, Roll Number : 2, Scores : 96 out of 100
Rohit scores well...

Example 2: In this example, we will display the result of the Parent class method also inside the child’s class overridden parent class method using the super keyword.




class Boy {
    name : string
    about() : void {
        console.log(this.name +" is an intelligent boy..")
    }
}
   
class Student extends Boy {
    rollnumber : number;
    marks: number;
    constructor(rollnumber : number, marks : number, 
    name1 : string){
        super(); 
        this.rollnumber = rollnumber
        this.name = name1
        this.marks = marks
    }
    displayStudentInformation() : void {
        console.log("Name : "+ this.name +", Roll Number : "
        this.rollnumber +", 
        Scores : " + this.marks + " out of 100" )
    }
    about() : void {
        // Invokes parent class about() method here also.
        super.about(); 
        console.log(this.name + " scores well...")
    }
  
let student = new Student(2, 96, "Rohit");
student.displayStudentInformation();
student.about();

Output:

Name : Rohit, Roll Number : 2, Scores : 96 out of 100
Rohit is an intelligent boy..
Rohit scores well...

Reference: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-3.html#override-and-the—noimplicitoverride-flag


Article Tags :