请用接口实现以下UML图 ,Java程序:测试类中,有三个柱体,分别以三角形,圆形,矩形为底面积,求它们的体积。 测试用例::三角形边:(3,4,5);圆形半径:2; 矩形边(3,4),柱体高:6.
时间: 2024-06-13 17:08:21 浏览: 109
以下是Java程序的实现,其中定义了Geometry接口和Circle、Triangle、Rectangle三个类来实现UML图中的三个形状,最后在Test类中计算柱体的体积:
```java
interface Geometry {
double getArea();
}
class Circle implements Geometry {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
class Triangle implements Geometry {
private double a, b, c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}
class Rectangle implements Geometry {
private double length, width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
}
public class Test {
public static void main(String[] args) {
Circle circle = new Circle(2);
Triangle triangle = new Triangle(3, 4, 5);
Rectangle rectangle = new Rectangle(3, 4);
double height = 6;
double volume1 = circle.getArea() * height;
double volume2 = triangle.getArea() * height;
double volume3 = rectangle.getArea() * height;
System.out.println("圆柱体体积:" + volume1);
System.out.println("三角柱体体积:" + volume2);
System.out.println("矩形柱体体积:" + volume3);
}
}
```
输出结果为:
```
圆柱体体积:75.39822368615503
三角柱体体积:36.0
矩形柱体体积:72.0
```
阅读全文