1 / 35

Chapter 9

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);.

Download Presentation

Chapter 9

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 9 Inheritance and Interfaces

  2. Figure 1 Inheritance Diagram

  3. Inheritance • class SavingsAccount extends BankAccount{ new methods new instance variables} • Existing methods are inherited:SavingsAccount collegeFund = new SavingsAccount(10);collegeFund.deposit(500);

  4. 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”

  5. 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;}

  6. Figure 2 Layout of a Subclass Object

  7. 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);

  8. 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)

  9. Figure 3 Object Variables of Different Types Refer to the Same Object

  10. Figure 4 A Part of the Hierarchy of Ancient Reptiles

  11. Figure 5 A Part of the Hierarchy of Swing User Interface Components

  12. Figure 6 Inheritance Hierarchy for Bank Account Classes

  13. 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

  14. 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

  15. Figure 7 Shadowing Instance Variables

  16. 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;}

  17. 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

  18. 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;}

  19. 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;}

  20. 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

  21. 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

  22. Figure 8 Polymorphism

  23. 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);

  24. 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 }

  25. 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()); } }

  26. 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.

  27. 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

  28. 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

  29. 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()

  30. Figure 9 The ObjectClass Is the Superclass of Every Java Class

  31. 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]

  32. 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;}

  33. 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();

  34. Figure 10 Cloning Objects

  35. Figure 11 The Object.cloneMethod Makes a Shallow Copy

More Related