JAVA继承练习:继承与多态

Circle:定义了基本的圆的属性和计算圆面积的方法。

Cylinder:继承自Circle类,添加了圆柱的高度属性,并覆写了findArea()方法来计算圆柱的表面积,增加了findVolume()方法来计算体积。

TestCylinder:测试创建圆柱对象并输出其表面积和体积。

class Circle {
    protected double radius;

    // 构造方法,将半径初始化为1
    public Circle() {
        this.radius = 1.0;
    }

    // 设置半径
    public void setRadius(double radius) {
        this.radius = radius;
    }

    // 获取半径
    public double getRadius() {
        return radius;
    }

    // 计算圆的面积
    public double findArea() {
        return 3.14 * radius * radius;
    }
}
class Cylinder extends Circle {
    private double length;

    // 构造方法,将长度初始化为1
    public Cylinder() {
        this.length = 1.0;
    }

    // 设置圆柱的长度
    public void setLength(double length) {
        this.length = length;
    }

    // 获取圆柱的长度
    public double getLength() {
        return length;
    }

    // 重写findArea方法,计算圆柱的表面积
    @Override
    public double findArea() {
        // 表面积 = 2 * 圆的面积 + 侧面积(2 * pi * r * h)
        return 2 * super.findArea() + 2 * 3.14 * radius * length;
    }

    // 计算圆柱的体积
    public double findVolume() {
        // 体积 = 圆的面积 * 高
        return super.findArea() * length;
    }
}
class TestCylinder {
    public static void main(String[] args) {
        // 创建Cylinder对象
        Cylinder cylinder = new Cylinder();

        // 设置圆柱的底面半径和高
        cylinder.setRadius(1);  // 半径设置为2
        cylinder.setLength(1);  // 高度设置为1

        // 输出圆柱的表面积和体积
        System.out.println("Cylinder surface area:" + cylinder.findArea());
        System.out.println("Cylinder volume:" + cylinder.findVolume());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值