需求:
这个小案例可以复习和理解多态的知识。
实现:
1.创建Card类(父类)
package com.itheima.demo2;
public class Card {
private String carId;
private String name;
private double money;
private String phone;
public Card() {
}
public Card(String carId, String name, double money, String phone) {
this.carId = carId;
this.name = name;
this.money = money;
this.phone = phone;
}
public String getCarId() {
return carId;
}
public void setCarId(String carId) {
this.carId = carId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
//预存金额
public void deposit(double money) {
this.money += money;
}
//消费金额
public void consume(double money) {
this.money -= money;
}
}
2.创建金卡和银卡类
金卡和银卡需要继承至Card类,并且重写comsume方法,并且提供有参构造器
金:
package com.itheima.demo2;
public class GoldCard extends Card{
public GoldCard(String carId, String name, double money, String phone) {
super(carId, name, money, phone);
}
@Override
public void consume(double money){
System.out.println("您当前消费"+money);
System.out.println("尊贵的金卡用户打折后消费"+money*0.8);
if(money*0.8>getMoney()) {
System.out.println("余额不足,请充值");
return;
}
setMoney(getMoney()-money*0.8);
if(money*0.8>=200) {
System.out.println("请打印洗车票");
}
}
}
银:
package com.itheima.demo2;
public class YingCard extends Card{
public YingCard(String carId, String name, double money, String phone) {
super(carId, name, money, phone);
}
@Override
public void consume(double money){
System.out.println("您当前消费"+money);
System.out.println("尊贵的银卡用户打折后消费"+money*0.9);
if(money*0.9>getMoney()) {
System.out.println("余额不足,请充值");
return;
}
setMoney(getMoney()-money*0.9);
}
}
3.创建对象,实现方法
package com.itheima.demo2;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
GoldCard gold = new GoldCard("渝A9999", "张三", 5000, "12345678901");
YingCard ying = new YingCard("渝A0000", "李四", 2000, "12347852901");
pay(gold);
pay(ying);
}
public static void pay(Card c){
System.out.println("当前消费:");
Scanner sc=new Scanner(System.in);
double money=sc.nextDouble();
c.consume(money);
}
}
这里pay方法直接传入Card类,利用多态的特点,不用多加金银卡的判断。
运行结果:
当前消费:
600
您当前消费600.0
尊贵的金卡用户打折后消费480.0
请打印洗车票
当前消费:
2230
您当前消费2230.0
尊贵的银卡用户打折后消费2007.0
余额不足,请充值
好了,就这样了,写的不详细,在图书馆,电脑没电马上关机了┭┮﹏┭┮。 理解一下。