Java测试类中,有三个柱体,分别以三角形,圆形,矩形为底面积,用接口实现求它们的体积
时间: 2024-06-13 16:08:42 浏览: 109
以下是Java测试类中,使用接口实现求三个柱体体积的示例代码:
```java
public class Test {
public static void main(String[] args) {
// 创建三个底面不同的柱体对象
Triangle triangle = new Triangle(3, 4);
Circle circle = new Circle(2);
Rectangle rectangle = new Rectangle(2, 3);
// 创建一个柱状对象
Pillar pillar = new Pillar();
// 使用接口实现求三个柱体体积
double volume1 = pillar.getVolume(triangle, 5);
double volume2 = pillar.getVolume(circle, 5);
double volume3 = pillar.getVolume(rectangle, 5);
// 输出结果
System.out.println("三角形底面积为:" + triangle.getArea() + ",高为5的柱体体积为:" + volume1);
System.out.println("圆形底面积为:" + circle.getArea() + ",高为5的柱体体积为:" + volume2);
System.out.println("矩形底面积为:" + rectangle.getArea() + ",高为5的柱体体积为:" + volume3);
}
}
// 抽象类Geometry
abstract class Geometry {
public abstract double getArea();
}
// 圆形类Circle
class Circle extends Geometry {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
// 矩形类Rectangle
class Rectangle extends Geometry {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
}
// 三角形类Triangle
class Triangle extends Geometry {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
}
// 接口IVolume
interface IVolume {
double getVolume(Geometry geometry, double height);
}
// 柱状类Pillar
class Pillar implements IVolume {
@Override
public double getVolume(Geometry geometry, double height) {
return geometry.getArea() * height;
}
}
```
阅读全文