面试题答案
一键面试// 抽象类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;
}
}
多态性的体现:
- 在这个代码中,
Circle
和Rectangle
类都继承自抽象类Shape
,并各自实现了calculateArea
方法。 - 当使用
Shape
类型来引用Circle
或Rectangle
的实例时,调用calculateArea
方法会根据实际对象的类型(即Circle
或Rectangle
)来执行对应的计算逻辑。例如:
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
实际指向Circle
或Rectangle
实例,calculateArea
方法的执行逻辑会根据实际对象类型不同而不同,这就是多态性的体现,即相同的操作(调用calculateArea
方法)作用于不同类型的对象上会产生不同的行为。