2014年4月9日 星期三

練習 4: 匿名類別

續練習3: 銀行臨時舉行促銷活動,凡定期存款客戶查詢帳號餘額時,會告知客戶,而顯示「本銀行定額存款10萬以上,另有優惠,請多加利用」訊息。 提示:在查詢時,以匿名類別實作

檔案:Account.java
package bank2;

public abstract class Account {
 int balance;
 Account(int money) {
   balance = money;
 }
 public abstract int inquiry();
}


檔案:AccountException.java
package bank2;

public class AccountException extends Exception {
  
 public String getMessage() // 覆寫 Throwable 的 toString()
 {
  return "金額不可以為負數";
 }
 
 public void showMessage() { // 自定方法
  System.out.println("例外發生:請從新輸入金額");
 }
}


檔案:DemandDepositAccount.java
package bank2;

public class DemandDepositAccount extends Account {
 
 DemandDepositAccount(int money){
  super(money);
 }
 
 public void deposit(int money) throws AccountException {
  if (money < 0) {
   throw new AccountException();
  }
  else
   balance += money;
 }
 
 public void withdraw(int money) throws AccountException{
  if (money < 0)
   throw new AccountException();
  else
   balance -= money;
 }

 public int inquiry() {
  return balance;
 }
}


檔案:FixedDepositAccount.java
package bank2;

public class FixedDepositAccount extends Account {

 FixedDepositAccount(int money) {
  super(money);
  // TODO Auto-generated constructor stub
 }

 public FixedDepositAccount() {
  // TODO Auto-generated constructor stub
  super(50000);
 }

 @Override
 public int inquiry() {
  // TODO Auto-generated method stub
  (new FixedDepositAccount() {
   public void showMe(){
    System.out.println("本銀行定額存款10萬以上,另有優惠,請多加利用");
   }
  }).showMe();
  
  return balance;
 }
}


檔案:AccountTest.java
package bank2;

public class AccountTest {

 public static void main(String[] args) {

  try{
   DemandDepositAccount demandDepositAcc = new DemandDepositAccount(1000);
   demandDepositAcc.deposit(500);
   demandDepositAcc.withdraw(300);
   System.out.println("活期賬戶餘額:" + demandDepositAcc.inquiry());
   
   FixedDepositAccount fixedDepositAcc = new FixedDepositAccount(20000);   
   System.out.println("定期賬戶餘額:" + fixedDepositAcc.inquiry());
   
  }
  catch(AccountException e){
   System.out.println(e.toString());
   e.showMessage();
  } 
 }

}
執行結果

沒有留言:

張貼留言