JAVA定义一个快递包裹类Package,并由此派生出普通包裹类和加急包裹类。要求:(1)Package类应包含寄件人和收件人姓名、地址和包裹重量属性,按重量*10计费。(2)普通包裹增加首重计费和超首重后部分的的每公斤计费单价属性,按首重+超重*每公斤计费单价计算总费用。(3)加急包裹没有首重限制,但有加急起价费用属性,按加急起价费+重量*10+加急公里数*0.02计算总费用。(4)为每个类添加calculateCost计算快递费用方法。编写测试程序,创建每种包裹类的对象并测试calculateCost方法
时间: 2024-02-28 11:52:25 浏览: 66
快递计算系统(java)
4星 · 用户满意度95%
好的,以下是JAVA定义的快递包裹类Package,并由此派生出普通包裹类和加急包裹类的代码,以及测试程序。
```java
class Package {
String senderName;
String senderAddress;
String receiverName;
String receiverAddress;
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;
}
}
class NormalPackage extends Package {
double firstWeight;
double unitPrice;
public NormalPackage(String senderName, String senderAddress, String receiverName, String receiverAddress, double weight, double firstWeight, double unitPrice) {
super(senderName, senderAddress, receiverName, receiverAddress, weight);
this.firstWeight = firstWeight;
this.unitPrice = unitPrice;
}
@Override
public double calculateCost() {
if (weight <= firstWeight) {
return super.calculateCost();
} else {
return firstWeight * 10 + (weight - firstWeight) * unitPrice;
}
}
}
class ExpressPackage extends Package {
double urgentPrice;
double mileage;
public ExpressPackage(String senderName, String senderAddress, String receiverName, String receiverAddress, double weight, double urgentPrice, double mileage) {
super(senderName, senderAddress, receiverName, receiverAddress, weight);
this.urgentPrice = urgentPrice;
this.mileage = mileage;
}
@Override
public double calculateCost() {
return urgentPrice + weight * 10 + mileage * 0.02;
}
}
public class TestPackage {
public static void main(String[] args) {
Package p1 = new Package("张三", "北京市朝阳区", "李四", "上海市浦东区", 2);
System.out.println("普通包裹费用:" + p1.calculateCost());
NormalPackage p2 = new NormalPackage("张三", "北京市朝阳区", "李四", "上海市浦东区", 3, 1, 0.5);
System.out.println("普通包裹费用:" + p2.calculateCost());
ExpressPackage p3 = new ExpressPackage("张三", "北京市朝阳区", "李四", "上海市浦东区", 4, 20, 100);
System.out.println("加急包裹费用:" + p3.calculateCost());
}
}
```
在测试程序中,我们创建了一个普通包裹对象p1、一个普通包裹对象p2和一个加急包裹对象p3,并分别调用它们的calculateCost方法计算快递费用。输出结果如下:
```
普通包裹费用:20.0
普通包裹费用:16.5
加急包裹费用:80.8
```
阅读全文