面试题答案
一键面试// 基类
class Animal {
makeSound(): void {
console.log('动物发出声音');
}
}
// 子类1
class Dog extends Animal {
makeSound(): void {
console.log('汪汪汪');
}
}
// 子类2
class Cat extends Animal {
makeSound(): void {
console.log('喵喵喵');
}
}
// 展示多态效果
function makeAnimalSound(animal: Animal) {
animal.makeSound();
}
const dog = new Dog();
const cat = new Cat();
makeAnimalSound(dog);
makeAnimalSound(cat);