TypeScript 方法覆盖

TypeScript 方法覆盖

在本文中,我们将了解与方法覆盖相关的一些必要细节,进一步,我们将看到如何在TypeScript中实现方法覆盖。

方法覆盖:

  • 方法覆盖是指派生类中的方法(相同的方法和签名)覆盖了基类(或父类)中的方法的过程。
  • 在这个过程中,子类中的方法可以使用或不使用父类中定义的逻辑。
  • 为了调用基类的方法或属性,我们可以使用 super 关键字,它可以帮助我们将基类的特定方法或属性调用到子类中。
  • 方法覆盖在我们想要在子类中改变父类的任何方法的行为时非常有用。

在分析了TypeScript中方法覆盖的所有基本事实之后,现在让我们看一下如何使用以下一些示例来实现TypeScript中的方法覆盖。

示例1: 在这个示例中,我们将声明两个类,并在父类中声明一个方法,子类将使用自己的逻辑来覆盖该方法。

Javascript

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();

输出:

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

示例2: 在这个示例中,我们将使用 super 关键字,在子类的覆盖父类方法中显示父类方法的结果。

Javascript

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();

输出:

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

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程