用Java编写接口实现,测试类中,有三个柱体,分别以三角形,圆形,矩形为底面积,求它们的体积。 测试用例::三角形边:(3,4,5);圆形半径:2; 矩形边(3,4),柱体高:6.
时间: 2024-06-13 22:08:19 浏览: 97
三角形问题的等价类测试
以下是Java代码实现,用于计算三个柱体的体积:
```java
public interface Geometry {
double getArea();
double getCircum();
}
class Circle implements Geometry {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getCircum() {
return 2 * Math.PI * radius;
}
}
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;
}
public double getCircum() {
return 2 * (length + width);
}
}
class Square implements Geometry {
private double side;
public Square(double side) {
this.side = side;
}
public double getArea() {
return side * side;
}
public double getCircum() {
return 4 * side;
}
}
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));
}
public double getCircum() {
return a + b + c;
}
}
class Cylinder {
private Geometry base;
private double height;
public Cylinder(Geometry base, double height) {
this.base = base;
this.height = height;
}
public double getVolume() {
return base.getArea() * height;
}
public double getSurfaceArea() {
return base.getCircum() * height + 2 * base.getArea();
}
}
public class AppTest {
public static void main(String[] args) {
// 三角形柱体
Triangle triangle = new Triangle(3, 4, 5);
Cylinder cylinder1 = new Cylinder(triangle, 6);
System.out.println("三角形柱体的体积为:" + cylinder1.getVolume());
// 圆形柱体
Circle circle = new Circle(2);
Cylinder cylinder2 = new Cylinder(circle, 6);
System.out.println("圆形柱体的体积为:" + cylinder2.getVolume());
// 矩形柱体
Rectangle rectangle = new Rectangle(3, 4);
Cylinder cylinder3 = new Cylinder(rectangle, 6);
System.out.println("矩形柱体的体积为:" + cylinder3.getVolume());
}
}
```
阅读全文