14 繼承

14.1 簡介

繼承是加強現有類別功能的方式。 如
    class SavingsAccount extends BankAccount
    {   new methods
        new instance variables
    }
SavingsAccount 繼承 BankAccount 中所有的方法和個例變數。 例如, SavingsAccount 可使用 BankAccount 中的 deposit 方法:
    SavingsAccount collegeFund = new SavingsAccount(10);
    collegeFund.deposit(500);
SavingsAccount 是 BankAccount 的子類別(subclass), 而後者是前者的母類別(superclass)。
    public class SavingsAccount extends BankAccount
    {  public SavingsAccount(double rate) { constructor implementation }
       public void addInterest() { method implementation }
       private double interestRate;
    }

實現 SavingAccount

14.2 子類別的建構

類別 CheckingsAccount
    public class CheckingsAccount extends BankAccount
    {  public CheckingsAccount(double d) { . . . }
       public void deposit(double d) { . . . }
       public void withdraw(double d) { . . . }
       public void deduceFee() { . . . }

       private int transactionCount;
    }
建構子類別時,可引用母類別的建構器(用 super( )):
    public CheckingAccount(int initialBalance)
    {  // construct superclass
       super(initialBalance);

       // initialize transaction count
       transactionCount = 0;
    }

14.3 方法的繼承

設計 CheckingAccount 的 deposit, 也可引用其母類別的 deposit, 如
    public void deposit(double amount)
    {  transactionCount++;
       // now add amount to balance
       super.deposit(amount);
    }

例題: CheckingAccount.java

14.4 同名異形(Polymorphism)

在該用母類別的地方, 可用子類別的物件, 如
    public void transfer(BankAccount other, double amount)
    { withdraw(amount);
      other.deposit(amount);
    }
處理銀行帳戶之間款項的轉移, 其中 other 為 BankAccount 的物件。 在
    BankAccount collegeFund = . . . ;
    CheckingAccount harrysChecking = . . . ;
    collegeFund.transfer(harrysChecking, 1000);
中, harrysChecking 是 CheckingAccount 的物件。 但是當引用 deposit 時, 似乎用的是 BankAccount 的 deposit(因為other 是 BankAccount 的物件), 實際上用的是 CheckingAccount 的 deposit。 這種方法的引用,由實際物件的類別決定,稱為同名異形(Polymorphism)。

例題: AccountTest.java