面试题答案
一键面试// 定义基类Shape
class Shape {
color: string;
position: { x: number; y: number };
constructor(color: string, x: number, y: number) {
this.color = color;
this.position = { x, y };
}
}
// 定义Circle子类
class Circle extends Shape {
radius: number;
constructor(color: string, x: number, y: number, radius: number) {
super(color, x, y);
this.radius = radius;
}
calculateArea(): number {
return Math.PI * this.radius * this.radius;
}
calculatePerimeter(): number {
return 2 * Math.PI * this.radius;
}
}
// 定义Rectangle子类
class Rectangle extends Shape {
width: number;
height: number;
constructor(color: string, x: number, y: number, width: number, height: number) {
super(color, x, y);
this.width = width;
this.height = height;
}
calculateArea(): number {
return this.width * this.height;
}
calculatePerimeter(): number {
return 2 * (this.width + this.height);
}
}
// 定义Triangle子类
class Triangle extends Shape {
side1: number;
side2: number;
side3: number;
constructor(color: string, x: number, y: number, side1: number, side2: number, side3: number) {
super(color, x, y);
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
calculateArea(): number {
const s = (this.side1 + this.side2 + this.side3) / 2;
return Math.sqrt(s * (s - this.side1) * (s - this.side2) * (s - this.side3));
}
calculatePerimeter(): number {
return this.side1 + this.side2 + this.side3;
}
}
如何扩展新的图形类型
- 创建新的子类:定义一个新的类,继承自
Shape
基类。例如,要添加一个Ellipse
图形类型,可以这样写:
class Ellipse extends Shape {
majorAxis: number;
minorAxis: number;
constructor(color: string, x: number, y: number, majorAxis: number, minorAxis: number) {
super(color, x, y);
this.majorAxis = majorAxis;
this.minorAxis = minorAxis;
}
calculateArea(): number {
return Math.PI * this.majorAxis * this.minorAxis;
}
calculatePerimeter(): number {
// 这里使用一个近似公式
return Math.PI * (3 * (this.majorAxis + this.minorAxis) - Math.sqrt((3 * this.majorAxis + this.minorAxis) * (this.majorAxis + 3 * this.minorAxis)));
}
}
- 使用新的子类:在代码中,就可以像使用其他子类一样使用新创建的
Ellipse
类。例如:
const ellipse = new Ellipse('red', 0, 0, 5, 3);
console.log(`Ellipse Area: ${ellipse.calculateArea()}`);
console.log(`Ellipse Perimeter: ${ellipse.calculatePerimeter()}`);
通过这种方式,利用TypeScript的继承和多态特性,新图形类型的扩展变得非常方便,只需按照基类的模式定义新的子类,并实现特定的面积和周长计算方法即可。