在 TypeScript 中,类的继承是一种创建新类的方式,新类称为子类或派生类,继承自一个现有的类,称为基类或父类。继承使得子类可以复用父类的属性和方法,同时也可以扩展或修改它们的行为。
TS快速入门-类-继承
继承的基本语法
在 TypeScript 中,使用 extends
关键字来实现继承:
class BaseClass {
public baseProp: string;
constructor(baseProp: string) {
this.baseProp = baseProp;
}
public baseMethod(): void {
console.log('Base method');
}
}
class DerivedClass extends BaseClass {
public derivedProp: number;
constructor(baseProp: string, derivedProp: number) {
super(baseProp); // 调用父类的构造函数
this.derivedProp = derivedProp;
}
public derivedMethod(): void {
console.log('Derived method');
}
}
重写方法
子类可以重写父类的方法,提供自己的实现:
class Animal {
makeSound(): void {
console.log('Some sound');
}
}
class Dog extends Animal {
makeSound(): void {
super.makeSound(); // 调用父类的方法
console.log('Bark');
}
}
访问修饰符
public
:子类可以访问父类的public
成员。protected
:子类可以访问父类的protected
成员,但不能访问private
成员。private
:子类无法访问父类的private
成员。
构造函数和继承
子类的构造函数需要首先调用 super()
来确保父类的构造函数被执行,这通常在子类构造函数的第一行代码中完成:
class Person {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
protected role: string;
constructor(name: string, role: string) {
super(name); // 调用父类的构造函数
this.role = role;
}
}
静态继承
子类也可以继承父类的静态成员,使用 super
关键字来访问它们:
class MathUtils {
static pi: number = 3.14;
static calculateCircleArea(radius: number): number {
return MathUtils.pi * radius * radius;
}
}
class GeometryUtils extends MathUtils {
static calculateSphereVolume(radius: number): number {
return 4 / 3 * MathUtils.pi * radius ** 3;
}
}
示例代码
以下是一个使用 TypeScript 类继承的示例:
// 定义基类
class Vehicle {
make: string;
model: string;
year: number;
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
startEngine(): void {
console.log('Engine started.');
}
}
// 定义子类,继承自 Vehicle
class Car extends Vehicle {
numDoors: number;
constructor(make: string, model: string, year: number, numDoors: number) {
super(make, model, year); // 调用父类构造函数
this.numDoors = numDoors;
}
honkHorn(): void {
console.log('Honk honk!');
}
// 重写父类方法
startEngine(): void {
super.startEngine(); // 调用父类方法
console.log('Car engine started.');
}
}
// 使用子类
let myCar = new Car('Tesla', 'Model 3', 2021, 4);
myCar.startEngine(); // Car engine started.
myCar.honkHorn(); // Honk honk!
TypeScript 中类继承的使用,包括如何调用父类构造函数、重写方法以及访问父类的属性和方法。继承是面向对象编程中的一个核心概念,它允许代码复用并建立在现有功能之上。