java定义一个快递包裹类 Package ,并由此派生出普通包裹类和加急包裹类。要求: (1) Package 类应包含寄件人和收件人姓名、地址和包裹重量属性,按重量*10计费。(2)普通包裹增加首重计费和超首重后部分的的每公斤计费单价属性,按首重+超重*每公斤计费单价计算总费用。 (3)加急包裹没有首重限制,但有加急起价费用属性,按加急起价费+重 (4)为每个类添加 calculateCost 计算快递费用方法。编写测试程序,创建 量*10+加急公里数*0.02计算总费用。 每种包裹类的对象并测试 calculateCost 方法。
时间: 2024-03-23 15:43:44 浏览: 54
好的,这是一个比较具体的编程问题,我可以为您提供一个Java的实现示例,您可以参考一下:
```
// 定义 Package 类
class Package {
private String senderName;
private String senderAddress;
private String receiverName;
private String receiverAddress;
private double weight; // 单位为千克
public Package(String senderName, String senderAddress, String receiverName, String receiverAddress, double weight) {
this.senderName = senderName;
this.senderAddress = senderAddress;
this.receiverName = receiverName;
this.receiverAddress = receiverAddress;
this.weight = weight;
}
public double calculateCost() {
return weight * 10;
}
// getter 和 setter 方法
}
// 定义普通包裹类
class OrdinaryPackage extends Package {
private double firstWeight;
private double excessFee; // 超出首重后的每公斤计费单价
public OrdinaryPackage(String senderName, String senderAddress, String receiverName, String receiverAddress, double weight, double firstWeight, double excessFee) {
super(senderName, senderAddress, receiverName, receiverAddress, weight);
this.firstWeight = firstWeight;
this.excessFee = excessFee;
}
public double calculateCost() {
if (weight <= firstWeight) {
return super.calculateCost();
} else {
return firstWeight * 10 + (weight - firstWeight) * excessFee;
}
}
// getter 和 setter 方法
}
// 定义加急包裹类
class UrgentPackage extends Package {
private double startingFee; // 加急起价费用
public UrgentPackage(String senderName, String senderAddress, String receiverName, String receiverAddress, double weight, double startingFee) {
super(senderName, senderAddress, receiverName, receiverAddress, weight);
this.startingFee = startingFee;
}
public double calculateCost() {
return startingFee + super.calculateCost();
}
// getter 和 setter 方法
}
// 测试程序
public class Main {
public static void main(String[] args) {
Package p1 = new Package("张三", "北京市朝阳区", "李四", "上海市浦东新区", 2.5);
OrdinaryPackage op1 = new OrdinaryPackage("张三", "北京市朝阳区", "李四", "上海市浦东新区", 2.5, 1.0, 3.0);
UrgentPackage up1 = new UrgentPackage("张三", "北京市朝阳区", "李四", "上海市浦东新区", 2.5, 50.0);
System.out.println("普通包裹1的费用为:" + op1.calculateCost());
System.out.println("加急包裹1的费用为:" + up1.calculateCost());
}
}
```
在这个示例中,Package 类包含了寄件人和收件人姓名、地址和包裹重量属性,并定义了 calculateCost 方法用于计算快递费用。OrdinaryPackage 类和 UrgentPackage 类都继承了 Package 类,并在其基础上增加了额外的属性和 calculateCost 方法的实现。最后,在测试程序中创建了几个对象并调用了它们的 calculateCost 方法,输出了它们的费用。
阅读全文