class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): void {
console.log('Generic animal sound');
}
}
class Dog extends Animal {
makeSound(): void {
console.log('Woof!');
}
}
class Cat extends Animal {
makeSound(): void {
console.log('Meow!');
}
}
// 通过多态性统一调用不同动物的叫声
function makeAnimalSound(animal: Animal) {
animal.makeSound();
}
const dog = new Dog('Buddy');
const cat = new Cat('Whiskers');
makeAnimalSound(dog);
makeAnimalSound(cat);
- 定义
Animal
类:
- 包含一个
name
属性用于存储动物的名字。
- 构造函数用于初始化
name
属性。
makeSound
方法定义了通用的动物叫声,这里是一个简单的默认输出。
- 定义
Dog
类:
- 继承自
Animal
类。
- 重写
makeSound
方法,使其输出狗的叫声“Woof!”。
- 定义
Cat
类:
- 继承自
Animal
类。
- 重写
makeSound
方法,使其输出猫的叫声“Meow!”。
- 多态性调用:
- 定义
makeAnimalSound
函数,它接受一个Animal
类型的参数。
- 无论传入的是
Dog
实例还是Cat
实例,函数都会调用对应的重写后的makeSound
方法,这就是多态性的体现。
- 创建
Dog
和Cat
的实例,并将它们传入makeAnimalSound
函数,实现统一调用不同动物的叫声。