第5章:类与面向对象编程
5.5 抽象类与接口实现
1. 抽象类(Abstract Class)
抽象类是一种不能被直接实例化的类,它用于定义其他派生类(子类)的通用结构和行为。抽象类通过 abstract 关键字声明,可以包含:
- 抽象方法:只有声明没有实现,子类必须重写。
- 具体方法:可以有默认实现,子类可选择是否重写。
示例代码
abstract class Animal {
abstract makeSound(): void; // 抽象方法
move(): void { // 具体方法
console.log("Moving...");
}
}
class Dog extends Animal {
makeSound(): void { // 必须实现抽象方法
console.log("Bark!");
}
}
const dog = new Dog();
dog.makeSound(); // 输出: Bark!
dog.move(); // 输出: Moving...
2. 接口实现(Interface Implementation)
接口(interface)用于定义类的公共契约,而类可以通过 implements 关键字实现一个或多个接口。与抽象类不同:
- 接口不能包含具体实现,只能定义属性和方法的签名。
- 类必须实现接口中定义的所有成员。
示例代码
interface Loggable {
log(message: string): void;
}
class ConsoleLogger implements Loggable {
log(message: string): void {
console.log(`[LOG]: ${message}`);
}
}
const logger = new ConsoleLogger();
logger.log("Hello, TypeScript!"); // 输出: [LOG]: Hello, TypeScript!
3. 抽象类与接口的区别
| 特性 | 抽象类 | 接口 |
|---|---|---|
| 实例化 | ❌ 不能直接实例化 | ❌ 不能实例化 |
| 实现方法 | 可包含具体方法和抽象方法 | 只能定义签名,无实现 |
| 多继承 | ❌ 单继承 | ✅ 可实现多个接口 |
| 访问修饰符 | 支持(public/private等) | 默认为 public |
| 使用场景 | 提供通用基类逻辑 | 定义行为契约 |
4. 结合使用抽象类与接口
在实际开发中,可以同时使用抽象类和接口,例如:
abstract class Shape {
abstract area(): number;
}
interface Drawable {
draw(): void;
}
class Circle extends Shape implements Drawable {
constructor(private radius: number) { super(); }
area(): number {
return Math.PI * this.radius ** 2;
}
draw(): void {
console.log("Drawing a circle");
}
}
5. 实际应用场景
- 框架设计:如 Angular 的
@Component装饰器依赖抽象类。 - 插件系统:通过接口定义插件必须实现的方法。
- 多态设计:抽象类提供基础逻辑,接口扩展额外能力。
最佳实践:优先使用接口定义轻量级契约,当需要共享代码时再使用抽象类。
