2. 用java定义一个快递包裹类 Package,并由此派生出普通包裹类和加急包裹类。 要求: (1)Package 类应包含寄件人和收件人姓名、地址和包裹重量属性,按重量*10 计费。 (2)普通包裹增加首重计费和超首重后部分的
时间: 2024-03-18 13:39:51 浏览: 58
计费规则,加急包裹在普通包裹的基础上增加加急费用。具体的Java代码实现如下:
```java
// Package 类
public class Package {
private String senderName;
private String senderAddress;
private String recipientName;
private String recipientAddress;
private int weight; // 单位为 g
public Package(String senderName, String senderAddress, String recipientName, String recipientAddress, int weight) {
this.senderName = senderName;
this.senderAddress = senderAddress;
this.recipientName = recipientName;
this.recipientAddress = recipientAddress;
this.weight = weight;
}
public int getWeight() {
return weight;
}
public double getCost() {
return weight * 0.1;
}
}
// 普通包裹类
public class OrdinaryPackage extends Package {
private static final int FIRST_WEIGHT = 1000; // 首重 g
private static final double FIRST_COST = 10.0; // 首重计费
private static final double EXTRA_COST = 5.0; // 超首重后部分的计费
public OrdinaryPackage(String senderName, String senderAddress, String recipientName, String recipientAddress, int weight) {
super(senderName, senderAddress, recipientName, recipientAddress, weight);
}
@Override
public double getCost() {
int weight = getWeight();
if (weight <= FIRST_WEIGHT) {
return FIRST_COST;
} else {
return FIRST_COST + (weight - FIRST_WEIGHT) * EXTRA_COST;
}
}
}
// 加急包裹类
public class ExpressPackage extends OrdinaryPackage {
private static final double EXPRESS_COST = 20.0; // 加急费用
public ExpressPackage(String senderName, String senderAddress, String recipientName, String recipientAddress, int weight) {
super(senderName, senderAddress, recipientName, recipientAddress, weight);
}
@Override
public double getCost() {
return super.getCost() + EXPRESS_COST;
}
}
```
使用示例:
```java
Package p1 = new Package("Alice", "123 Main St", "Bob", "456 Elm St", 500);
System.out.println(p1.getCost()); // 输出 50.0
OrdinaryPackage p2 = new OrdinaryPackage("Alice", "123 Main St", "Bob", "456 Elm St", 1500);
System.out.println(p2.getCost()); // 输出 15.0
ExpressPackage p3 = new ExpressPackage("Alice", "123 Main St", "Bob", "456 Elm St", 1500);
System.out.println(p3.getCost()); // 输出 35.0
```
阅读全文