package exception;
public class Account {
protected double balance;
public Account(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void deposit(double amt){
this.balance+=amt;
}
public void withdraw(double amt) throws OverDraftException{
if(this.balance<amt)
throw new OverDraftException("余额不足", amt-this.balance);
this.balance-=amt;
}
public static void main(String[] args) {
//开户存了1000
Account a = new Account(1000);
//存钱1000
a.deposit(1000);
//查看余额
System.out.println(a.getBalance());
try {
//取2001
a.withdraw(2001);
} catch (OverDraftException e) {
System.err.println("透支金额:"+e.getDeficit());
e.printStackTrace();
}
}
}
package exception;
public class OverDraftException extends Exception{
private double deficit;
public double getDeficit() {
return deficit;
}
public OverDraftException(String msg, double deficit) {
super(msg);
this.deficit = deficit;
}
}
package exception;
public class CheckingAccount extends Account {
private double overdraftProtection;
public CheckingAccount(double balance) {
super(balance);
}
public CheckingAccount(double balance, double overdraftProtection) {
super(balance);
this.overdraftProtection = overdraftProtection;
}
public void withdraw(double amt) throws OverDraftException {
if (amt > this.balance + overdraftProtection) {
double deficit = amt - (this.balance + overdraftProtection);
throw new OverDraftException("透支额度超标", deficit);
}
this.balance -= amt;
}
public static void main(String[] args) {
//开户存了1000块,拥有500的透支额度
CheckingAccount a = new CheckingAccount(1000, 500);
//存了1000
a.deposit(1000);
//查询余额
System.out.println(a.getBalance());
try {
a.withdraw(600);
System.out.println(a.getBalance());
a.withdraw(600);
System.out.println(a.getBalance());
a.withdraw(600);
System.out.println(a.getBalance());
a.withdraw(600);
System.out.println(a.getBalance());
a.withdraw(600);
System.out.println(a.getBalance());
} catch (OverDraftException e) {
System.err.println("透支超额:"+e.getDeficit());
e.printStackTrace();
}
}
}
本文介绍了如何在Java中实现银行账户类,包括基本的账户操作如存款和取款,以及处理透支情况的OverDraftException异常。通过CheckingAccount子类演示了透支保护功能。
892

被折叠的 条评论
为什么被折叠?



