2006年12月24日 星期日

繼承

先前談到了 Account 物件
適用來處理帳戶
有一個帳戶名稱、編號、存款餘額
但當我們來思考 SavingAccount 儲蓄存款的時候
我們會寫一個全新的 SavingAccount 物件
會發現也有一個帳戶名稱、編號、存款餘額,
只是多了一個利率 Rate

如果我們又要思考一個 CreditAccount 信用卡帳戶
又要寫一次 帳戶名稱、編號、存款餘額?
於是 '繼承' 的必要就產生了

擴充父類別
建立 SavingAccount.java 的時候擴充父類別
public class SavingAccount extends Account {
}
很厲害的地方就是
父類別所有功能就可以立刻使用了!
public class TestAccount {
 public static void main(String[] args) {
  SavingAccount sa = new SavingAccount ();
  sa.setNumber(101);
  sa.show();
 }
}
於是我們只要把屬性 rate 以及相關法加入即可
並且重新定義方法。
public class SavingAccount extends Account {
 private double rate;

 public void setRate(double rate){
  this.rate = rate;
 }

 public void show() {
  //不用寫同樣的東西了,是不很方便呢
  //System.out.println("Number: " + number);
  //System.out.println("Name: " + name);
  //System.out.println("Balance: " + balance);
  super.show();
  System.out.println("Rate: " + this.rate);
 }
}
所謂的重新定義,是 Account 方法中的 show 和
SavingAccount 中的 show 可能不完全相同
因此借用了部份父類別的 show()
同時增加自己所需要的程式碼

子類別的建構式
//建構式, 還是要有參數
public SavingAccount(int number, String name, double balance,double rate){
 //同樣的也不需要再重新建構一次
 //this.number = number;
 //this.name = name;
 //this.balance = balance;
 super(number, name, balance); //網父類別找, 找到三個參數
 this.rate = rate;
}
加入這行建構式以後
子類別的功能可說是如虎添翼了
SavingAccount sa = new SavingAccount (101,"Simon",200,0.02);
sa.show();
最後執行只需要這樣!
真是太漂亮了

快速建立子類別
信用卡的子程序,繼續繼承前述子程序
public class CreditAccount extends SavingAccount {
 private double limit;

 public CreditAccount(int number, String name, double balance, double rate, double limit){
  super(number, name, balance,rate); //使用父類別的建構式
  this.limit = limit;
 }

 public void show(){
 super.show();
  System.out.println("Rate: " + this.limit);
 }
 
 //信用卡專用的提款
 //使用 private 就可以用父類別的屬性了!

 public boolean withdraw(double amount) {
  if (balance + limit >= amount) {
   balance = balance - amount;
   if (balance < 0 ) {
   this.limit = this.limit + balance;
   }
   System.out.println("提款成功,您提了"+ amount +"元,剩餘額度"+ limit);
   return true;
  }
  else {
   System.out.println("餘款或額度不足,提款未執行");
   return false;
  }
 }
}
執行測試程式
public class TestAccount {
 public static void main(String[] args) {
  CreditAccount ca = new CreditAccount(101,"Simon",200,0.02,30000);
  ca.show();
  //信用卡的餘額很特殊,可以是負的
  //這裡使用的是信用卡 CreditAccount 裡的 withdraw 方法

  ca.withdraw(350);
  ca.show();
 }
}
保護類型
先前提到了 public 和 private 但還有一個重要的 protected,
這是允許子類別使用父類別的屬性。
這樣子類別才可以用前面的 (父類別) 屬性。

因此將 Account.java、SavingAccount.java 還有 CreditAccount.java 裡的
屬性的 private 都改為 protected (因為共用屬性的需要)

子類別的程式雖然少
但功能能夠繼續累積,非常有用!

沒有留言: