2014年4月9日 星期三

練習2 - 繼承, 抽象類別,抽象方法

續練習 1。沒有久,張三又去福爾摩沙銀行開立定期賬戶 Fixed Deposit。張三存入 30,000 元,約定一年後到期。此帳戶,銀行只提供餘額查詢的功能。 提示: 1. 以抽象類別、方法實作

檔案:Account.java
package bank2;

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



檔案:FixedDepositAccount.java
package bank2;

public class FixedDepositAccount extends Account {

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

 @Override
 public int inquiry() {
  // TODO Auto-generated method stub
  return balance;
 }
}


檔案:DemandDepositAccount.java
package bank2;

public class DemandDepositAccount extends Account {
 
 DemandDepositAccount(int money){
  super(money);
 }
 
 public void deposit(int money) {
  balance += money;
 }
 
 public void withdraw(int money){
  balance -= money;
 }

 public int inquiry() {
  return balance;
 }
}


檔案:AccountTest.java
package bank2;

import bank.DemandDepositAccount;

public class AccountTest {

 public static void main(String[] args) {
  DemandDepositAccount demandDepositAcc = new DemandDepositAccount(1000);
  demandDepositAcc.deposit(500);
  demandDepositAcc.withdraw(300);
  System.out.println("活期賬戶餘額:" + demandDepositAcc.inquiry());
  
  FixedDepositAccount fixedDepositAcc = new FixedDepositAccount(10000);
  System.out.println("定期存款餘額:" + fixedDepositAcc.inquiry());
 }

}

執行結果











沒有留言:

張貼留言