接口Geometry的代码如下:

public interface Geometry {
    public double getArea();
}

柱体类pillar的代码如下:

public class Pillar {
    private Geometry base;
    private double height;
    
    public Pillar(Geometry base, double height) {
        this.base = base;
        this.height = height;
    }
    
    public double getVolume() {
        return base.getArea() * height;
    }
}

圆形类的代码如下:

public class Circle implements Geometry {
    private double radius;
    
    public Circle(double radius) {
        this.radius = radius;
    }
    
    public double getArea() {
        return Math.PI * radius * radius;
    }
}

矩形类的代码如下:

public class Rectangle implements Geometry {
    private double width;
    private double height;
    
    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }
    
    public double getArea() {
        return width * height;
    }
}

测试类Test的代码如下:

public class Test {
    public static void main(String[] args) {
        Geometry circle = new Circle(2.0);
        Pillar pillar1 = new Pillar(circle, 5.0);
        System.out.println("The volume of the cylinder with a circle base and a height of 5 is " + pillar1.getVolume());
        
        Geometry rectangle = new Rectangle(3.0, 4.0);
        Pillar pillar2 = new Pillar(rectangle, 6.0);
        System.out.println("The volume of the cylinder with a rectangle base and a height of 6 is " + pillar2.getVolume());
    }
}

输出结果如下:

The volume of the cylinder with a circle base and a height of 5 is 62.83185307179586
The volume of the cylinder with a rectangle base and a height of 6 is 72.0
``
编写程序求柱体的体积1、为柱体的底面设计一个接口Geometry包含计算面积的方法getArea;2、为柱体设计类pillar要求:	a有两个成员变量底面和高度。底面是任何可以计算面积的几何形状。	b实现构造方法对成员变量赋值。	c包含成员方法计算柱体pillar的体积。 3、编写测试类圆形类、矩形类实现Geometry接口编写测试类Test分别用圆形、矩形作为柱体的底面并计算其体积。

原文地址: https://www.cveoy.top/t/topic/gAQD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录