用匿名类的接口实现以下UML图,java测试类中,有三个柱体,分别以三角形,圆形,矩形为底面积,求它们的体积。pillar类连接Geometry接口 。测试用例::三角形边:(3,4,5);圆形半径:2; 矩形边(3,4),柱体高:6.
时间: 2024-06-13 14:08:43 浏览: 164
以下是使用匿名类的接口实现UML图的Java代码,可以计算三角形、圆形和矩形柱体的体积:
```java
public interface Geometry {
double getArea();
}
class Pillar {
private Geometry bottom;
private double height;
public Pillar(Geometry bottom, double height) {
this.bottom = bottom;
this.height = height;
}
public double getVolume() {
return bottom.getArea() * height;
}
}
public class Test {
public static void main(String[] args) {
// 创建三角形底面积
Geometry triangle = new Geometry() {
double a = 3;
double b = 4;
double c = 5;
double p = (a + b + c) / 2;
@Override
public double getArea() {
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
};
// 创建圆形底面积
Geometry circle = new Geometry() {
double radius = 2;
@Override
public double getArea() {
return Math.PI * radius * radius;
}
};
// 创建矩形底面积
Geometry rectangle = new Geometry() {
double length = 3;
double width = 4;
@Override
public double getArea() {
return length * width;
}
};
// 创建三个柱体并计算体积
Pillar pillar1 = new Pillar(triangle, 6);
Pillar pillar2 = new Pillar(circle, 6);
Pillar pillar3 = new Pillar(rectangle, 6);
System.out.println("三角形柱体的体积为:" + pillar1.getVolume());
System.out.println("圆形柱体的体积为:" + pillar2.getVolume());
System.out.println("矩形柱体的体积为:" + pillar3.getVolume());
}
}
```
阅读全文