定义一个接口Shape,包含计算面积和计算周长的抽象方法;定义实现Shape的几种类,比如矩形、圆形、等边三角形 测试几种子类,求它们的面积和周长
时间: 2024-02-03 15:13:32 浏览: 135
以下是一个可能的实现,包括Shape接口和三个实现类Rectangle、Circle和EquilateralTriangle:
```java
public interface Shape {
double getArea();
double getPerimeter();
}
public class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
public class EquilateralTriangle implements Shape {
private double side;
public EquilateralTriangle(double side) {
this.side = side;
}
public double getArea() {
return Math.sqrt(3) / 4 * side * side;
}
public double getPerimeter() {
return 3 * side;
}
}
```
我们可以编写一个简单的测试程序来测试这些类:
```java
public class ShapeTest {
public static void main(String[] args) {
Shape rectangle = new Rectangle(5, 3);
Shape circle = new Circle(4);
Shape equilateralTriangle = new EquilateralTriangle(6);
System.out.println("Rectangle:");
System.out.println("Area: " + rectangle.getArea());
System.out.println("Perimeter: " + rectangle.getPerimeter());
System.out.println("Circle:");
System.out.println("Area: " + circle.getArea());
System.out.println("Perimeter: " + circle.getPerimeter());
System.out.println("Equilateral Triangle:");
System.out.println("Area: " + equilateralTriangle.getArea());
System.out.println("Perimeter: " + equilateralTriangle.getPerimeter());
}
}
```
输出结果应该是:
```
Rectangle:
Area: 15.0
Perimeter: 16.0
Circle:
Area: 50.26548245743669
Perimeter: 25.132741228718345
Equilateral Triangle:
Area: 15.588457268119896
Perimeter: 18.0
```
阅读全文