第5章:类与面向对象编程
继承与多态
1. 继承的基本概念
继承是面向对象编程的核心特性之一,允许子类(派生类)继承父类(基类)的属性和方法。TypeScript 使用 extends 关键字实现继承:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance}m.`);
}
}
class Dog extends Animal {
bark() {
console.log("Woof! Woof!");
}
}
const dog = new Dog("Buddy");
dog.bark(); // "Woof! Woof!"
dog.move(10); // "Buddy moved 10m."
2. 方法重写(Override)
子类可以重写父类的方法以实现特定行为,同时可通过 super 调用父类方法:
class Cat extends Animal {
constructor(name: string) {
super(name); // 必须调用父类构造函数
}
move(distance = 5) {
console.log("Slinking...");
super.move(distance); // 调用父类实现
}
}
3. 多态的实现
多态允许子类对象以父类类型被引用,但调用方法时仍执行子类实现:
class Bird extends Animal {
move(distance = 10) {
console.log("Flying...");
super.move(distance);
}
}
const animals: Animal[] = [new Dog("Rex"), new Cat("Whiskers"), new Bird("Tweetie")];
animals.forEach(animal => animal.move());
// 输出不同的移动方式,体现多态性
4. 抽象类与继承
抽象类(abstract)不能实例化,但可作为基类被继承,强制子类实现抽象成员:
abstract class Shape {
abstract getArea(): number;
}
class Circle extends Shape {
constructor(public radius: number) { super(); }
getArea() {
return Math.PI * this.radius ** 2;
}
}
5. 继承的注意事项
- 单一继承限制:TypeScript 不支持多继承(一个子类只能继承一个父类)
- 构造函数链:子类构造函数必须调用
super()且在使用this前完成 - 访问修饰符影响:
private成员不可被子类访问protected成员允许子类访问
- 静态成员继承:静态属性和方法也会被继承
6. 实际应用场景
- UI组件库:基础组件(如
BaseButton)通过继承扩展为具体组件 - 游戏开发:
GameObject基类派生出Player、Enemy等子类 - 企业应用:通用业务逻辑(如
BaseService)被具体服务继承
最佳实践:优先使用组合(对象包含)而非继承,避免过深的继承层次结构。继承适用于明确的 "is-a" 关系场景。
