MST

星途 面试题库

面试题:TypeScript中类的抽象和多态实现

请使用TypeScript实现一个抽象类`Shape`,包含抽象方法`calculateArea`。然后创建两个子类`Circle`和`Rectangle`继承自`Shape`,并分别实现`calculateArea`方法。同时阐述在这个过程中是如何体现多态性的。
20.2万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 抽象类Shape
abstract class Shape {
    // 抽象方法calculateArea
    abstract calculateArea(): number;
}

// Circle类继承自Shape
class Circle extends Shape {
    constructor(private radius: number) {
        super();
    }
    // 实现calculateArea方法
    calculateArea(): number {
        return Math.PI * this.radius * this.radius;
    }
}

// Rectangle类继承自Shape
class Rectangle extends Shape {
    constructor(private width: number, private height: number) {
        super();
    }
    // 实现calculateArea方法
    calculateArea(): number {
        return this.width * this.height;
    }
}

多态性的体现

  1. 在这个代码中,CircleRectangle类都继承自抽象类Shape,并各自实现了calculateArea方法。
  2. 当使用Shape类型来引用CircleRectangle的实例时,调用calculateArea方法会根据实际对象的类型(即CircleRectangle)来执行对应的计算逻辑。例如:
let shapes: Shape[] = [];
shapes.push(new Circle(5));
shapes.push(new Rectangle(4, 6));

for (let shape of shapes) {
    console.log(shape.calculateArea());
}

这里shape的静态类型是Shape,但在运行时,shape实际指向CircleRectangle实例,calculateArea方法的执行逻辑会根据实际对象类型不同而不同,这就是多态性的体现,即相同的操作(调用calculateArea方法)作用于不同类型的对象上会产生不同的行为。