在TypeScript中,继承是一种允许我们从另一个类接收属性和方法的机制,这使得代码更加模块化和可复用。TypeScript 完全支持面向对象的编程模式,包括继承。
使用继承的步骤:
- 定义基类(父类): 先定义一个基本的类,它提供了一些基础的方法和属性,其他类可以从这个基类继承这些方法和属性。
- 定义派生类(子类): 通过使用关键字
extends
创建一个新的类,这个新类继承了基类的属性和方法。 - 重写方法 (可选): 在子类中,可以重写继承自父类的方法以提供更具体的功能。
- 使用
super
调用父类构造函数和方法 (可选): 在子类的构造函数中,你可以使用super()
调用父类的构造函数。此外,也可以在子类方法中通过super
关键字调用父类的方法。
示例代码:
假设我们有一个基类 Vehicle
,它有一些基本属性如 brand
和方法如 displayInfo()
:
typescriptclass Vehicle { brand: string; constructor(brand: string) { this.brand = brand; } displayInfo(): void { console.log(`This vehicle is made by ${this.brand}.`); } }
现在,我们创建一个名为 Car
的子类,它继承了 Vehicle
类,并添加了一个新的属性 model
和一个新的方法 displayDetailedInfo()
:
typescriptclass Car extends Vehicle { model: string; constructor(brand: string, model: string) { super(brand); // 调用父类的构造函数 this.model = model; } displayDetailedInfo(): void { console.log(`This car is a ${this.brand} ${this.model}.`); } // 重写父类的方法 displayInfo(): void { super.displayInfo(); // 调用父类的 displayInfo() console.log(`It is specifically a ${this.model}.`); } }
使用示例:
typescriptlet myCar = new Car("Toyota", "Corolla"); myCar.displayInfo(); // 输出: This vehicle is made by Toyota. It is specifically a Corolla. myCar.displayDetailedInfo(); // 输出: This car is a Toyota Corolla.
这个例子展示了如何通过继承和方法重写以及如何使用 super
关键字来调用父类的方法和构造函数。这些特性使得 TypeScript 在处理复杂的对象层次结构时非常有用且易于管理。
2024年7月29日 13:33 回复