使用typescript 1、 创建一个接口Shape,接口中定义两个方法getArea()与getLength()分别用于求图形面积与周长。定义两个图形类Circle(属性:radius 半径)与Square(属性:width length)实现该接口,在构造方法中分别初始化半径与长宽,调用getArea()与getLength()计算图形面积与周长。
时间: 2023-12-14 17:36:31 浏览: 76
可以按照以下代码实现:
```typescript
interface Shape {
getArea(): number;
getLength(): number;
}
class Circle implements Shape {
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 {
width: number;
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);
}
}
```
可以这样使用:
```typescript
const circle = new Circle(5);
console.log(circle.getArea()); // 78.53981633974483
console.log(circle.getLength()); // 31.41592653589793
const square = new Square(3, 4);
console.log(square.getArea()); // 12
console.log(square.getLength()); // 14
```
阅读全文