设计一个接口Shape,其中包含计算面积和周长的抽象方法。 设计三个类:矩形类、圆形类和三角形类实现该接口,分别计算自己的面积和周长,并在测试类中测试这三个类的功能。 要求: Shape接口中应该包含计算面积和周长的抽象方法。 Circle、Rectangle和Triangle类应该实现Shape接口,并分别实现自己的计算面积和周长的方法。 在测试类中,创建三个类的对象,并调用它们的计算面积和周长的方法。
时间: 2024-02-25 17:57:01 浏览: 72
好的,以下是实现上述要求的Java代码:
接口Shape:
```
public interface Shape {
public double getArea();
public double getPerimeter();
}
```
矩形类Rectangle:
```
public class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
}
```
圆形类Circle:
```
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;
}
}
```
三角形类Triangle:
```
public class Triangle implements Shape {
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getArea() {
double p = (side1 + side2 + side3) / 2;
return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
}
public double getPerimeter() {
return side1 + side2 + side3;
}
}
```
测试类TestShape:
```
public class TestShape {
public static void main(String[] args) {
Shape circle = new Circle(5);
System.out.println("Circle area: " + circle.getArea());
System.out.println("Circle perimeter: " + circle.getPerimeter());
Shape rectangle = new Rectangle(3, 4);
System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Rectangle perimeter: " + rectangle.getPerimeter());
Shape triangle = new Triangle(3, 4, 5);
System.out.println("Triangle area: " + triangle.getArea());
System.out.println("Triangle perimeter: " + triangle.getPerimeter());
}
}
```
运行测试类TestShape的输出结果如下:
```
Circle area: 78.53981633974483
Circle perimeter: 31.41592653589793
Rectangle area: 12.0
Rectangle perimeter: 14.0
Triangle area: 6.0
Triangle perimeter: 12.0
```
可以看到,三个类都实现了Shape接口,并成功计算出了自己的面积和周长。
阅读全文