用接口实现以下UML图,java测试类中,有三个柱体,分别以三角形,圆形,矩形为底面积,求它们的体积。pillar类连接Geometry接口 。测试用例::三角形边:(3,4,5);圆形半径:2; 矩形边(3,4),柱体高:6.
时间: 2024-06-13 08:08:43 浏览: 123
以下是实现UML图的Java代码:
```java
// Geometry接口
interface Geometry {
double getArea();
}
// Circle类
class Circle implements Geometry {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
// Rectangle类
class Rectangle implements Geometry {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
}
// Triangle类
class Triangle implements Geometry {
private double a;
private double b;
private double 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));
}
}
// Pillar类
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) {
Circle circle = new Circle(2);
Rectangle rectangle = new Rectangle(3, 4);
Triangle triangle = new Triangle(3, 4, 5);
Pillar pillar1 = new Pillar(circle, 6);
Pillar pillar2 = new Pillar(rectangle, 6);
Pillar pillar3 = new Pillar(triangle, 6);
System.out.println("圆柱体的体积为:" + pillar1.getVolume());
System.out.println("矩形柱体的体积为:" + pillar2.getVolume());
System.out.println("三角形柱体的体积为:" + pillar3.getVolume());
}
}
```
输出结果为:
```
圆柱体的体积为:75.39822368615503
矩形柱体的体积为:72.0
三角形柱体的体积为:36.0
```
阅读全文