用Java编写程序,用匿名类实现,测试类中,有三个柱体,分别以三角形,圆形,矩形为底面积,求它们的体积。 测试用例::三角形边:(3,4,5);圆形半径:2; 矩形边(3,4),柱体高:6.
时间: 2024-06-13 12:08:42 浏览: 85
以下是Java编写程序,使用匿名类实现,计算三个柱体体积的代码:
```java
public class AppTest {
public static void main(String[] args) {
// 圆柱体积
double radius = 2;
double height = 6;
Geometry cylinder = new Geometry() {
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getCircum() {
return 2 * Math.PI * radius;
}
};
double cylinderVolume = cylinder.getArea() * height;
System.out.println("圆柱体积:" + cylinderVolume);
// 矩形柱体积
double length = 3;
double width = 4;
Geometry rectangularPrism = new Geometry() {
@Override
public double getArea() {
return length * width;
}
@Override
public double getCircum() {
return 2 * (length + width);
}
};
double rectangularPrismVolume = rectangularPrism.getArea() * height;
System.out.println("矩形柱体积:" + rectangularPrismVolume);
// 三角形柱体积
double a = 3;
double b = 4;
double c = 5;
Geometry triangularPrism = new Geometry() {
@Override
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
@Override
public double getCircum() {
return a + b + c;
}
};
double triangularPrismVolume = triangularPrism.getArea() * height;
System.out.println("三角形柱体积:" + triangularPrismVolume);
}
}
abstract class Geometry {
public abstract double getArea();
public abstract double getCircum();
}
```
阅读全文