MST
星途 面试题库

面试题:TypeScript 类继承中如何重写方法并体现多态性

请用TypeScript代码示例,创建一个父类`Animal`,包含`makeSound`方法。再创建两个子类`Dog`和`Cat`,分别继承自`Animal`类,并对`makeSound`方法进行重写,以展示多态性。解释代码中是如何通过类的继承链实现多态的。
11.5万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义父类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方法。DogCat类继承自Animal类,并重写了makeSound方法以实现各自特定的行为。

多态性通过以下方式实现:

  1. 继承DogCat类继承了Animal类,获得了Animal类的属性和方法,同时可以对这些方法进行重写。
  2. 方法重写DogCat类重写了Animal类的makeSound方法,使得不同的子类对象在调用makeSound方法时,会执行各自重写后的代码,表现出不同的行为。
  3. 统一接口testSound函数接受一个Animal类型的参数,这样无论是Dog还是Cat对象,都可以作为参数传入该函数,调用其makeSound方法。函数并不关心具体传入的是哪个子类的对象,只需要对象具有makeSound方法,从而实现了多态性。