简述如何在TypeScript中实现继承?
参考答案:
在TypeScript中,类继承是面向对象编程的一个重要概念。它允许我们创建一个新的类(称为子类),该类继承自一个已存在的类(称为父类或超类)。子类会继承父类的所有属性和方法,同时还可以定义自己的新属性和方法。
以下是一个在TypeScript中实现类继承的基本示例:
// 定义一个父类
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
move(): void {
console.log(`${this.name} moves.`);
}
}
// 定义一个子类,继承自Animal类
class Snake extends Animal {
constructor(name: string) { super(name); }
move(): void {
console.log("Slithering...");
super.move(); // 调用父类的move方法
}
sayHello(): void {
console.log("Hello, I'm a snake.");
}
}
// 创建一个Snake实例
let sam = new Snake("Sam");
sam.move(); // 输出 "Slithering...Sam moves."
sam.sayHello(); // 输出 "Hello, I'm a snake."
在这个例子中,Snake
类继承了Animal
类。Snake
类中的constructor
函数通过super
关键字调用了Animal
类的constructor
函数,传递了name
参数。
Snake
类也重写了move
方法,但在重写的方法中,通过super.move()
调用了Animal
类的move
方法。这就是如何在TypeScript中实现类继承,并如何调用父类方法的示例。
需要注意的是,子类可以添加新的属性和方法,也可以覆盖父类的属性和方法。但是,子类不能删除父类的属性或方法。