建立一个Account类: 银行账号属性: balance 余额属性: name 姓名 方法: getBalance() 获取余额方法: deposit() 存钱方法: withdraw()

 


public class Account {
    public float balance;
    public float deficit = 0;

    public Account() {
    }

    public Account(float balance, float deficit) {
        this.balance = balance;
        this.deficit = deficit;
    }

    class OverdraftException extends Exception {
        public OverdraftException() {

        }

        public OverdraftException(String msg) {
            super(msg);
        }
    }

    public float getBalance() {
        return balance;
    }

    public void setBalance(float balance) {
        this.balance = balance;
    }

    public void deposit(float money) {
        balance = balance + money;
        System.out.println("存款成功!余额为" + balance);
    }

    public void withdraw(float money) throws OverdraftException {
        if (balance > money) {
            balance = balance - money;
            System.out.println("取款成功!余额为" + balance);
        }
    }
}

class checkingAccount extends Account {
    private float overdraftProtection = 2000;

    public checkingAccount() {
    }

    public checkingAccount(float balance, float deficit) {
        super(balance, deficit);
    }

    @Override
    public void withdraw(float money) throws OverdraftException {
        if (money <= balance) {
            super.withdraw(money);
        } else if (money > balance) {
            if (money < (balance + overdraftProtection)) {
                deficit = (balance - money);
                float deficit1 = deficit;
                //第三个变量实现对deficit的复制 并作为下个透支额的基础
                setBalance(0);
                overdraftProtection += deficit;
                //透支额为
                System.out.println("账户余额为:" + getBalance() + "透支额度为" + deficit + "可以透支的余额为" + overdraftProtection);
                deficit += deficit1;
            } else {
                System.out.println("账户余额为:" + getBalance() + "透支额度为" + deficit + "可透支额度为" + overdraftProtection);
                throw new OverdraftException("超出可以支配的额度");
            }
        }

    }
}

class CheckDemo {
    public static void main(String[] args) {
        checkingAccount ck = new checkingAccount(1000, 2000);
        ck.deposit(400);
        ck.deposit(600);
        try {
            ck.withdraw(1900);
            ck.withdraw(500);
            ck.withdraw(900);
            ck.withdraw(900);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  • 6
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值