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