某小区物业为了更好的服务住户,为空巢老人和单亲家庭发放社区购物优惠证。空巢老人优惠证和单亲家庭可以享受购物打折优惠,具体优惠力度视家庭情况而定,空巢老人优惠证在8折的基础上,每多一个老人折扣减1到1.5之间不定(最多两个老人),单亲家庭优惠证在9折的基础上,每多一个孩子,折扣减0.5-1之间不定(最多5个孩子)。持证到物业处,输入家庭单人享受的减少折扣,可以查询优惠证的折扣力度。请依据题目完成下列题目: 设计优惠证抽象类Discount,包含家庭类型和享受优惠人数两个封装属性,为属性添加setter和getter方法;定义抽象方法返回优惠证可每次消费享受的折扣费用 public abstract double getDiscount(int peopleCount);其中peopleCount为单人享受的折扣减少折扣。
时间: 2024-02-03 08:11:43 浏览: 15
以下是 Discount 抽象类的代码实现:
```java
public abstract class Discount {
private String familyType; // 家庭类型
private int peopleCount; // 可享受优惠的人数
public Discount(String familyType, int peopleCount) {
this.familyType = familyType;
this.peopleCount = peopleCount;
}
public String getFamilyType() {
return familyType;
}
public void setFamilyType(String familyType) {
this.familyType = familyType;
}
public int getPeopleCount() {
return peopleCount;
}
public void setPeopleCount(int peopleCount) {
this.peopleCount = peopleCount;
}
public abstract double getDiscount(int peopleCount); // 抽象方法返回优惠折扣
}
```
在 Discount 抽象类中,定义了家庭类型和享受优惠人数两个属性,并为其添加了 setter 和 getter 方法。同时,也定义了一个抽象方法 getDiscount(int peopleCount),用于返回优惠折扣。
在上述题目中,有两种优惠证:空巢老人优惠证和单亲家庭优惠证。因此,我们可以通过继承 Discount 抽象类来实现这两种优惠证的具体实现。
以下是空巢老人优惠证类的代码实现:
```java
public class EmptyNestElderlyDiscount extends Discount {
private int elderlyCount; // 老人数量
public EmptyNestElderlyDiscount(int elderlyCount) {
super("空巢老人", 1); // 家庭类型为“空巢老人”,可享受优惠人数为1
this.elderlyCount = elderlyCount;
}
public int getElderlyCount() {
return elderlyCount;
}
public void setElderlyCount(int elderlyCount) {
this.elderlyCount = elderlyCount;
}
@Override
public double getDiscount(int peopleCount) {
// 计算折扣力度
double discount = 0.8; // 基础折扣为8折
if (elderlyCount >= 1 && elderlyCount <= 2) {
discount -= elderlyCount * 0.1; // 每多一个老人折扣减少0.1
} else if (elderlyCount > 2) {
discount -= 0.15; // 最多两个老人,超过两个老人折扣只减少0.15
}
return discount;
}
}
```
在 EmptyNestElderlyDiscount 类中,我们定义了 elderlyCount 属性表示老人数量,并重写了 getDiscount(int peopleCount) 方法来计算优惠折扣。
以下是单亲家庭优惠证类的代码实现:
```java
public class SingleParentFamilyDiscount extends Discount {
private int childCount; // 孩子数量
public SingleParentFamilyDiscount(int childCount) {
super("单亲家庭", 1); // 家庭类型为“单亲家庭”,可享受优惠人数为1
this.childCount = childCount;
}
public int getChildCount() {
return childCount;
}
public void setChildCount(int childCount) {
this.childCount = childCount;
}
@Override
public double getDiscount(int peopleCount) {
// 计算折扣力度
double discount = 0.9; // 基础折扣为9折
if (childCount >= 1 && childCount <= 5) {
discount -= childCount * 0.05; // 每多一个孩子折扣减少0.05
} else if (childCount > 5) {
discount -= 0.25; // 最多五个孩子,超过五个孩子折扣只减少0.25
}
return discount;
}
}
```
在 SingleParentFamilyDiscount 类中,我们定义了 childCount 属性表示孩子数量,并重写了 getDiscount(int peopleCount) 方法来计算优惠折扣。
通过继承 Discount 抽象类,我们可以在每个优惠证类中实现自己的特殊逻辑。