如何在TypeScript中实现继承?
在面向对象编程中,继承是一种基本的机制,它允许我们创建一个新类(子类)来继承另一个类(父类)的属性和方法。TypeScript支持类继承,并且提供了一套丰富的语法来实现这一功能。
1. 类继承
在TypeScript中,我们使用extends关键字来实现类的继承。子类可以访问父类的公共和受保护成员,但不能访问私有成员。
// 父类
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
public speak(): void {
console.log(`My name is ${this.name} and I can speak.`);
}
}
// 子类
class Dog extends Animal {
public speak(): void {
console.log(`Woof! My name is ${this.name} and I can speak.`);
}
}
// 使用子类
const dog = new Dog('Rex');
dog.speak(); // 输出: Woof! My name is Rex and I can speak.
在这个例子中,我们定义了一个Animal类和一个从Animal继承的Dog类。Dog类重写了speak方法,以提供自己的实现。
2. 访问父类的构造函数
在子类中,我们可以使用super关键字来访问父类的构造函数。这对于在子类的构造函数中初始化继承的属性非常有用。
class Person {
private name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public introduce(): void {
console.log(`Hello, my name is ${this.name} and I work in ${this.department}.`);
}
}
const employee = new Employee('Alice', 'Engineering');
employee.introduce(); // 输出: Hello, my name is Alice and I work in Engineering.
在这个例子中,Employee类继承了Person类,并在其构造函数中调用了父类的构造函数来初始化name属性。同时,Employee类还添加了一个新的属性department。
3. 重写方法
子类可以重写父类的方法,以提供自己的实现。这在实现多态行为时非常有用。
class Vehicle {
public move(): void {
console.log('The vehicle moves.');
}
}
class Car extends Vehicle {
public move(): void {
console.log('The car moves.');
}
}
const vehicle = new Vehicle();
const car = new Car();
vehicle.move(); // 输出: The vehicle moves.
car.move(); // 输出: The car moves.
在这个例子中,Car类重写了Vehicle类的move方法,以提供特定的行为。
4. 访问父类的成员
子类可以访问父类的公共和受保护成员,但不能访问私有成员。
class Base {
public baseMethod(): void {
console.log('This is a public method in Base.');
}
protected baseProtectedMethod(): void {
console.log('This is a protected method in Base.');
}
// private basePrivateMethod(): void {
// console.log('This is a private method in Base.');
// }
}
class Derived extends Base {
public derivedMethod(): void {
this.baseMethod(); // 允许
this.baseProtectedMethod(); // 允许
// this.basePrivateMethod(); // 不允许,会报错
}
}
const derived = new Derived();
derived.derivedMethod(); // 输出: This is a public method in Base.
在这个例子中,Derived类可以访问Base类的公共方法baseMethod和受保护方法baseProtectedMethod,但不能访问私有方法basePrivateMethod。