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; }
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; }
public void deposit(double amount) { transactionCount++; // now add amount to balance super.deposit(amount); }
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