目录
1. 定义圆类(Circle)
2. 定义圆柱体类(Cylinder)
3. 测试圆柱体类
4. 总结
        在Java中,我们可以通过面向对象的方式来模拟现实世界中的物体,比如圆柱体。本篇文章将通过一个简单的示例来展示如何定义一个圆柱体类(Cylinder),并计算其体积。此外,我们还将创建一个圆类(Circle)作为基类,因为圆柱体的底面本质上是一个圆。
根据下图实现类。在CylinderTest类中创建Cylinder类的对象,设置圆柱的底面半径和高,并输出圆柱的体积。

1. 定义圆类(Circle)
首先,我们需要定义一个圆类Circle,它包含圆的半径和计算圆面积的方法。
package exer5;  
  
public class Circle {  
    private double radius;  
  
    // 无参构造函数,默认半径为1  
    public Circle() {  
        radius = 1;  
    }  
  
    // 带参数的构造函数  
    public Circle(double radius) {  
        this.radius = radius;  
    }  
  
    // 获取半径  
    public double getRadius() {  
        return radius;  
    }  
  
    // 设置半径  
    public void setRadius(double radius) {  
        this.radius = radius;  
    }  
  
    // 计算圆的面积  
    public double findArea(){  
        return Math.PI * radius * radius; // 注意这里应该是半径的平方  
    }  
}注意:在findArea方法中,我们使用了Math.PI来表示圆周率,并且圆的面积计算公式是πr²。
2. 定义圆柱体类(Cylinder)
        接着,我们定义一个圆柱体类Cylinder,它继承自Circle类,并添加了圆柱体的高(length)属性和计算体积的方法。
package exer5;  
  
public class Cylinder extends Circle{  
    private double length;  
  
    // 无参构造函数,默认半径为1,高也为1  
    public Cylinder() {  
        super(); // 调用父类的无参构造函数  
        length = 1;  
    }  
  
    // 带高的构造函数  
    public Cylinder(double length) {  
        super(); // 同样调用父类的无参构造函数  
        this.length = length;  
    }  
  
    // 带半径和高的构造函数  
    public Cylinder(double radius, double length) {  
        super(radius); // 调用父类的带参数构造函数  
        this.length = length;  
    }  
  
    // 获取高  
    public double getLength() {  
        return length;  
    }  
  
    // 设置高  
    public void setLength(double length) {  
        this.length = length;  
    }  
  
    // 计算圆柱体的体积  
    public double findVolume(){  
        return findArea() * length; // 圆柱体体积 = 圆的面积 * 高  
    }  
}3. 测试圆柱体类
最后,我们创建一个测试类CylinderTest来实例化圆柱体对象,并计算其体积。
package exer5;  
  
public class CylinderTest {  
    public static void main(String[] args) {  
        Cylinder cy = new Cylinder(2.3, 1.4); // 创建圆柱体对象,半径为2.3,高为1.4  
  
        System.out.println("圆柱的体积为:" + cy.findVolume()); // 输出圆柱体的体积  
    }  
}4. 总结
        通过上述步骤,我们成功地定义了一个圆柱体类Cylinder,并通过继承圆类Circle来实现对圆柱体底面半径的管理。此外,我们还添加了计算圆柱体体积的方法,并通过测试类CylinderTest验证了代码的正确性。
面向对象编程的一个重要特点是代码的复用性和可扩展性。通过继承机制,我们可以很容易地重用已有的代码,并通过添加新的属性和方法来扩展类的功能。在这个例子中,通过



















