用Java编写程序,和接口有关的匿名类实现,测试类中,有三个柱体,分别以三角形,圆形,矩形为底面积,求它们的体积。 测试用例::三角形边:(3,4,5);圆形半径:2; 矩形边(3,4),柱体高:6
时间: 2024-06-13 07:08:20 浏览: 92
以下是Java编写的程序,使用接口和匿名类实现,计算三个柱体的体积:
```java
public interface Geometry {
double getArea();
}
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 Circle implements Geometry {
private double r;
public Circle(double r) {
this.r = r;
}
public double getArea() {
return Math.PI * r * r;
}
}
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 Main {
public static void main(String[] args) {
Geometry[] geometries = new Geometry[]{
new Triangle(3, 4, 5),
new Circle(2),
new Rectangle(3, 4)
};
double height = 6;
for (Geometry geometry : geometries) {
double volume = geometry.getArea() * height;
System.out.println("The volume of the cylinder is: " + volume);
}
}
}
```
输出结果为:
```
The volume of the cylinder is: 36.0
The volume of the cylinder is: 25.132741228718345
The volume of the cylinder is: 72.0
```
阅读全文