025-为什么要用抽象类

本文探讨了在Java中使用抽象类的原因,通过实例演示了抽象类在Student和Teacher类中的应用,并提及了与继承和多态的关系。作者拥有丰富的软件开发和教学经验,已录制多门涵盖Java基础到高级技术的视频课程,包括项目实战和源代码分享。
好的,我理解了你的问题。以下是答案: ``` // 抽象类 ElectricityCharge abstract class ElectricityCharge { protected double price; // 电价 // 计算电费 public double calculateFee(double electricity) { if (electricity <= 0) { return 0; } double fee = electricity * price; if (electricity > getBaseElectricity()) { fee += (electricity - getBaseElectricity()) * getExcessPrice(); } return fee; } // 获取基础用电量 protected abstract int getBaseElectricity(); // 获取超出部分的单价 protected abstract double getExcessPrice(); } // 丰水期电费类 ElectricityChargeOfRain class ElectricityChargeOfRain extends ElectricityCharge { public ElectricityChargeOfRain() { price = 2.25; } @Override protected int getBaseElectricity() { return 200; } @Override protected double getExcessPrice() { return 2.025; // 9折 } } // 枯水期电费类 ElectricityChargeLackRain class ElectricityChargeLackRain extends ElectricityCharge { public ElectricityChargeLackRain() { price = 3.5; } @Override protected int getBaseElectricity() { return 150; } @Override protected double getExcessPrice() { return 3.85; // 10% 加价 } } // 计算丰水期用电量为300度的电费 ElectricityCharge ec1 = new ElectricityChargeOfRain(); double fee1 = ec1.calculateFee(300); System.out.println("丰水期用电量为300度的电费为:" + fee1 + "元"); // 计算枯水期用电量为230度的电费 ElectricityCharge ec2 = new ElectricityChargeLackRain(); double fee2 = ec2.calculateFee(230); System.out.println("枯水期用电量为230度的电费为:" + fee2 + "元"); ``` 输出结果: ``` 丰水期用电量为300度的电费为:675.0元 枯水期用电量为230度的电费为:920.5元 ``` 以上代码中,ElectricityCharge 是抽象类,包含了计算电费的方法 calculateFee 和两个抽象方法 getBaseElectricity 和 getExcessPrice。ElectricityChargeOfRain 和 ElectricityChargeLackRain 是具体的子类,分别实现了这两个抽象方法,计算出丰水期和枯水期的电费。最后通过调用 calculateFee 方法计算电费,并输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

优快云专家-赖老师(软件之家)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值