Introduction to Java - Abstract Class Case

case:

  • A gas station launched two types of payment cards, one is a gold card with 10,000 pre-stored, and enjoys a 20% discount on subsequent refueling, and the other is a silver card with a pre-deposited 5,000, and enjoys a 15% discount on subsequent refueling.
  • Please implement the logic after the two cards enter the cash register system. The cards need to contain the owner's name, balance, and payment functions.

1. Create a parent class Card:

public abstract class Card {
    private String userName;
    private double money;//卡片的余额

    /**
     *定义一个支付方法,表示卡片可以支付
     * 因为每张卡片的支付方式不一样,所以不能在父类中定死,
     * 但每张卡片都要执行支付功能且支付行为不一样,所以把支付手段定义为子类中的约定手段,使用抽象方法
     * nomey:代表消费的余额。
     */
    public abstract void pay(double nomey);

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
}

2. Create subclasses, gold card users and silver card users:

//金卡用户
public class GoldCard extends Card {
    @Override
    public void pay(double money02) {
        System.out.println("尊贵的金卡会员,您好。");
        System.out.println("您当前消费:" + money02 );
        System.out.println("您的卡片当前余额是:" + getMoney());
        //优惠价
        double rs = money02 * 0.8;
        System.out.println(getUserName() + "您实际消费为:" + rs);
        //更新账户余额,这里假设他当前余额大于消费余额
        setMoney(getMoney() - rs);
    }
}
//银卡用户
public class SilverCard extends Card{
    @Override
    public void pay(double money02) {
        System.out.println("尊贵的银卡卡会员,您好。");
        System.out.println("您当前消费:" + money02 );
        System.out.println("您的卡片当前余额是:" + getMoney());
        //优惠价
        double rs = money02 * 0.85;
        System.out.println(getUserName() + "您实际消费为:" + rs);
        //更新账户余额,这里假设他当前余额大于消费余额
        setMoney(getMoney() - rs);
    }
}

 3. Use an abstract class:

public class Demo {
    public static void main(String[] args) {
        //学习抽象类的基本使用:做父类,被继承,重写抽象方法
        GoldCard c = new GoldCard();
        c.setMoney(10000);
        c.setUserName("qing");
        c.pay(300);
        System.out.println("剩余:" + c.getMoney());

        SilverCard c1 = new SilverCard();
        c1.setMoney(10000);
        c1.setUserName("chen");
        c1.pay(300);
        System.out.println("剩余:" + c1.getMoney());
    }
}

Guess you like

Origin blog.csdn.net/weixin_61275790/article/details/129814009