360 likes | 505 Views
Chapter 9. Inheritance and Interfaces. Figure 1 Inheritance Diagram. Inheritance. class SavingsAccount extends BankAccount { new methods new instance variables } Existing methods are inherited : SavingsAccount collegeFund = new SavingsAccount(10); collegeFund.deposit(500);.
E N D
Chapter 9 Inheritance and Interfaces
Figure 1 Inheritance Diagram
Inheritance • class SavingsAccount extends BankAccount{ new methods new instance variables} • Existing methods are inherited:SavingsAccount collegeFund = new SavingsAccount(10);collegeFund.deposit(500);
Super- and subclasses • SavingsAccount is a subclass of BankAccount • Every savings account is a bank account (with additional properties) • BankAccount is a superclass of SavingsAccount • “Super/sub” doesn't mean “superior/inferiour”, but “general/specific”
Savings Account Class • public class SavingsAccountextends BankAccount{ public SavingsAccount(double rate) { interestRate = rate; } public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); } private double interestRate;}
Figure 2 Layout of a Subclass Object
Conversion to superclass • You can store a subclass reference in a superclass variable:SavingsAccount collegeFund = new SavingsAccount(10);BankAccount anAccount = collegeFund;Object anObject = collegeFund; • Can't apply subclass methods:anAccount.addInterest(); // ERROR • Useful for code reuse, generic programmingmomsChecking.transfer(collegeFund, 100);
More about Type Conversions • You can't convert between unrelated classes:Rectangle r = collegeFund; // NO • You can “cast back” to the original type:SavingsAccount s = (SavingsAccount) anObject; • If you lied about the type, a “bad cast” exception results • Use instanceof to check:if (anObject instanceof SavingsAccount)
Figure 3 Object Variables of Different Types Refer to the Same Object
Figure 4 A Part of the Hierarchy of Ancient Reptiles
Figure 5 A Part of the Hierarchy of Swing User Interface Components
Figure 6 Inheritance Hierarchy for Bank Account Classes
Subclass Methods • Overriding: Subclass defines a new method with the same name as a superclass method • Inheritance: Subclass does not redefine superclass method • New method: Subclass defines a method that does not exist in superclass
Subclass Variables • Subclass inherits all superclass variables—but cannot access the private superclass variables • Subclass can define new variables • Subclass variables with the same name as superclass variables don't override superclass variables
Figure 7 Shadowing Instance Variables
Checking Account • public class BankAccount{ public double getBalance() public void deposit(double d) public void withdraw(double d) private double balance;} • public class CheckingAccount{ public void deposit(double d) public void withdraw(double d) public void deductFees(); private int transactionCount;}
Checking Account • public void deposit(double amount){ transactionCount++; super.deposit(balance);} • Can't call balance = balance + amount;Can't access private data • Can't calldeposit(balance);That would be a recursive call
Time Deposit Account • public class TimeDepositAccount{ . . . public void addInterest() { periodsToMaturity--; super.addInterest(); } public void withdraw(double amount) { if (periodsToMaturity > 0) super.withdraw(PENALTY); super.withdraw(amount); } private int periodsToMaturity;}
Subclass Construction • Use super to call the superclass constructorpublic CheckingAccount(double initialBalance){ super(initialBalance); transactionCount = 0;}public TimeDepositAccount(double rate, int maturity){ super(rate); periodsToMaturity = maturity;}
Polymorphism • Recall transfer method:public void transfer(BankAccount other, double amount){ withdraw(amount); other.deposit(amount);} • Can pass any kind of BankAccount • Different withdraw, deposit methods are called depending on the subclass
Polymorphism • BankAccount collegeFund = . . .;CheckingAccount harrysChecking = . . .;collegeFund.transfer(harrysChecking, 1000);The checking account is charged a transaction fee • Methods are always determined by the type of the actual object, not the object reference • Polymorphic = of multiple shapes
Figure 8 Polymorphism
Program AccountTest.java public class AccountTest { public static void main(String[] args) { SavingsAccount momsSavings = new SavingsAccount(0.5); TimeDepositAccount collegeFund = new TimeDepositAccount(1, 3); CheckingAccount harrysChecking = new CheckingAccount(0); momsSavings.deposit(10000); collegeFund.deposit(10000); momsSavings.transfer.(harrysChecking, 2000); collegeFund.transfer.(harrysChecking, 980);
harrysChecking.withdraw(500); harrysChecking.withdraw(80); harrysChecking.withdraw(400); endOfMonth(momsSavings); endOfMonth(collegeFund); endOfMonth(harrysChecking); printBalance("mom's savings", momsSavings); // $10000 – $2000 + 0.5% interest = $8040 printBalance("the college fund", collegeFund); // $10000 – $980 – $20 penalty + 1% interest // = $9090 printBalance("Harry's checking", harrysChecking); // $2000 + $980 – $500 – $80 – $400 – $4 fees // = $1996 }
public static void endOfMonth(SavingsAccount savings) { savings.addInterest(); } public static void endOfMonth(CheckingAccount checking) { checking.deductFees(); } public static void printBalance(String name, BankAccount account) { System.out.println("The balance of ” + name + ” account is $” + account.getBalance()); } }
Interfaces • Interface is similar to a superclass • No instance variables • Methods are abstract—no definitions are provided in the interface • Methods are automatically public • A class can extend at most one superclass • A class can implement any number of super-interfaces.
Interfaces • Standard library has interface for object comparison:public interface Comparable{ int compareTo(Object other); // no implementation // no instance variables} • Class can choose to implement interface:class SavingsAccount implements Comparable • Class must supply implementation
Interfaces • Savings account class must supply method:public int compareTo(Object other){ SavingsAccount otherAccount = (SavingsAccount)other; if (interestRate < other.interestRate) return -1; if (interestRate > other.interestRate) return 1; return 0;} • Now the sort method in the Arrays class can sort an array of savings accounts
Object: The Cosmic Superclass • Every class that doesn't extend another class extends the library class xObject • Inherited methods: • String toString() • boolean equals(Object other) • Object clone()
Figure 9 The ObjectClass Is the Superclass of Every Java Class
Overriding toString • Return a string containing the object state • public String toString(){ return "BankAccount[balance=" + balance + "]";} • Automatically invoked when concatenating an object with a string:System.out.print("a=" + a);printsa=BankAccount[balance=5000]
Overriding equals • Check that two bank accounts are equal:public boolean equals(Object otherObject){ if(otherObject instanceof BankAccount) { BankAccount other = (BankAccount)otherObject; return balance == other.balance; } else return false;}
Overriding clone • Clone a bank account:public Object clone(){ BankAccount clonedAccount = new BankAccount(balance); return clonedAccount;} • Call clone:BankAccount account1 = . . .;BankAccount account2 = (BankAccount)account1.clone();
Figure 10 Cloning Objects
Figure 11 The Object.cloneMethod Makes a Shallow Copy