用接口有关的匿名类实现以下UML图,java测试类中,有三个柱体,分别以三角形,圆形,矩形为底面积,求它们的体积。pillar类连接Geometry接口 。测试用例::三角形边:(3,4,5);圆形半径:2; 矩形边(3,4),柱体高:6.
时间: 2024-06-13 16:08:43 浏览: 140
以下是实现UML图的Java代码,其中使用了接口和匿名类来实现Geometry接口:
```java
public interface Geometry {
double getArea();
}
public 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 Main {
public static void main(String[] args) {
// 创建三个底面分别为三角形、圆形、矩形的柱体
Pillar pillar1 = new Pillar(new Geometry() {
double a = 3, b = 4, c = 5;
double p = (a + b + c) / 2;
@Override
public double getArea() {
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}, 6);
Pillar pillar2 = new Pillar(new Geometry() {
double r = 2;
@Override
public double getArea() {
return Math.PI * r * r;
}
}, 6);
Pillar pillar3 = new Pillar(new Geometry() {
double a = 3, b = 4;
@Override
public double getArea() {
return a * b;
}
}, 6);
// 输出三个柱体的体积
System.out.println("三角形底面积为:" + pillar1.bottom.getArea() + ",高为6的柱体体积为:" + pillar1.getVolume());
System.out.println("圆形底面积为:" + pillar2.bottom.getArea() + ",高为6的柱体体积为:" + pillar2.getVolume());
System.out.println("矩形底面积为:" + pillar3.bottom.getArea() + ",高为6的柱体体积为:" + pillar3.getVolume());
}
}
```
输出结果为:
```
三角形底面积为:6.0,高为6的柱体体积为:108.0
圆形底面积为:12.566370614359172,高为6的柱体体积为:150.79644737231007
矩形底面积为:12.0,高为6的柱体体积为:72.0
```
阅读全文