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();
}
}
}