某小区物业为了更好的服务住户,为空巢老人和单亲家庭发放社区购物优惠证。空巢老人优惠证和单亲家庭可以享受购物打折优惠,具体优惠力度视家庭情况而定,空巢老人优惠证在8折的基础上,每多一个老人折扣减1到1.5之间不定(最多两个老人),单亲家庭优惠证在9折的基础上,每多一个孩子,折扣减0.5-1之间不定(最多5个孩子)。持证到物业处,输入家庭单人享受的减少折扣,可以查询优惠证的折扣力度。请依据题目完成下列题目: (1)设计优惠证抽象类Discount,包含家庭类型和享受优惠人数两个封装属性,为属性添加setter和getter方法;定义抽象方法返回优惠证可每次消费享受的折扣费用 public abstract double getDiscount(int peopleCount);其中peopleCount为单人享受的折扣减少折扣。(20分) (2)创建子类EmptyNestDiscount和SingleParentDiscount继承Discount类并实现getDiscount方法,依据优惠证类型和单人享受的减少折扣返回此优惠证的最终享受折扣(最终享受折扣=优惠证折扣基础 - 单人享受的减少折扣 * 享受优惠人数)(例如:空巢老人优惠证的单人享受减少折扣是1.2,家庭人数是2,那最终折扣为8-1.2*2=5.6折)。(20分) (3)在测试主类TestDiscount中以你的名字和张三创建两个优惠证,分别为空巢优惠证和单亲优惠证,分别设置家庭类型和享受优惠人数。(10分) 在测试主类TestDiscount创建static类型getInfo方法:public static void getInfo(Discount dc,double peopleDiscount)显示优惠证类别和优惠证的折扣力度。
时间: 2024-02-03 14:12:13 浏览: 71
(1) Discount.java
```java
public abstract class Discount {
private String familyType;
private int 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);
}
```
(2) EmptyNestDiscount.java
```java
public class EmptyNestDiscount extends Discount {
@Override
public double getDiscount(int peopleCount) {
double baseDiscount = 8.0;
int oldManCount = Math.min(2, getPeopleCount());
double discount = baseDiscount - peopleCount * oldManCount;
return discount < 1.0 ? 1.0 : discount;
}
}
```
SingleParentDiscount.java
```java
public class SingleParentDiscount extends Discount {
@Override
public double getDiscount(int peopleCount) {
double baseDiscount = 9.0;
int childCount = Math.min(5, getPeopleCount());
double discount = baseDiscount - peopleCount * childCount / 2.0;
return discount < 1.0 ? 1.0 : discount;
}
}
```
(3) TestDiscount.java
```java
public class TestDiscount {
public static void main(String[] args) {
Discount myDiscount = new EmptyNestDiscount();
myDiscount.setFamilyType("空巢老人");
myDiscount.setPeopleCount(2);
getInfo(myDiscount, 1.2);
Discount zhangDiscount = new SingleParentDiscount();
zhangDiscount.setFamilyType("单亲家庭");
zhangDiscount.setPeopleCount(3);
getInfo(zhangDiscount, 0.8);
}
public static void getInfo(Discount dc, double peopleDiscount) {
System.out.println(dc.getFamilyType() + "的优惠力度为:" + dc.getDiscount((int) peopleDiscount * 10) + "折");
}
}
```
阅读全文