面试题答案
一键面试// 定义父类Animal
class Animal {
makeSound() {
console.log('动物发出声音');
}
}
// 定义子类Dog,继承自Animal
class Dog extends Animal {
makeSound() {
console.log('汪汪汪');
}
}
// 定义子类Cat,继承自Animal
class Cat extends Animal {
makeSound() {
console.log('喵喵喵');
}
}
// 测试多态性
function testSound(animal: Animal) {
animal.makeSound();
}
const dog = new Dog();
const cat = new Cat();
testSound(dog);
testSound(cat);
在上述代码中,Animal
类是所有动物类的基类,它定义了一个通用的makeSound
方法。Dog
和Cat
类继承自Animal
类,并重写了makeSound
方法以实现各自特定的行为。
多态性通过以下方式实现:
- 继承:
Dog
和Cat
类继承了Animal
类,获得了Animal
类的属性和方法,同时可以对这些方法进行重写。 - 方法重写:
Dog
和Cat
类重写了Animal
类的makeSound
方法,使得不同的子类对象在调用makeSound
方法时,会执行各自重写后的代码,表现出不同的行为。 - 统一接口:
testSound
函数接受一个Animal
类型的参数,这样无论是Dog
还是Cat
对象,都可以作为参数传入该函数,调用其makeSound
方法。函数并不关心具体传入的是哪个子类的对象,只需要对象具有makeSound
方法,从而实现了多态性。