typescript创建一个接口Shape,接口中定义两个方法getArea()与getLength()分别用于求图形面积与周长。定义两个图形类Circle(属性:radius 半径)与Square(属性:width length)实现该接口,在构造方法中分别初始化半径与长宽,调用getArea()与getLength()计算图形面积与周长
时间: 2023-12-14 11:36:45 浏览: 72
以下是 TypeScript 的代码实现:
```typescript
interface Shape {
getArea(): number;
getLength(): number;
}
class Circle implements Shape {
private radius: number;
constructor(radius: number) {
this.radius = radius;
}
getArea(): number {
return Math.PI * this.radius ** 2;
}
getLength(): number {
return 2 * Math.PI * this.radius;
}
}
class Square implements Shape {
private width: number;
private length: number;
constructor(width: number, length: number) {
this.width = width;
this.length = length;
}
getArea(): number {
return this.width * this.length;
}
getLength(): number {
return 2 * (this.width + this.length);
}
}
// 测试代码
const circle = new Circle(5);
console.log(`圆的面积为:${circle.getArea()}`);
console.log(`圆的周长为:${circle.getLength()}`);
const square = new Square(4, 6);
console.log(`正方形的面积为:${square.getArea()}`);
console.log(`正方形的周长为:${square.getLength()}`);
```
输出结果:
```
圆的面积为:78.53981633974483
圆的周长为:31.41592653589793
正方形的面积为:24
正方形的周长为:20
```
阅读全文