Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture Notes – Inheritance (Ch 9-10)

Similar presentations


Presentation on theme: "Lecture Notes – Inheritance (Ch 9-10)"— Presentation transcript:

1 Lecture Notes – Inheritance (Ch 9-10)
Yonglei Tao

2 Inheritance An “is a” relationship between classes
Generalization and specialization Software reuse Employee Worker Manager

3 Extending a Class public class Employee { protected String name;
protected double basePay; public double getBasePay () { return basePay; } public void setBasePay ( doule amt ) { basePay = amt; } public String toString () { return “Name: “+name+“\nPay: “+basePay; } } public class Worker extends Employee { private double hours; public double getHours() { return hours; } public void setHours( double hrs ) { hours = hrs; } public String toString () { return super.toString()+“\nHours: “+hours; }

4 Syntax Inheritance

5 Syntax Calling a Superclass Method

6 Constructors // in class Employee public Employee () { }
public Employee (String name, double pay) { this.name = name; basePay = pay; } // in class Worker public Worker (String name, double pay, double hours) { super (name, pay); this.hours = hours;

7 Syntax Calling a Superclass Constructor

8 Polymorphic References
Worker w = new Worker(“Ed”, 9.25, 25); System.out.println (“Base Pay: “ + w.getBasePay()); System.out.println (w); Employee p; // a polymorphic reference p = new Worker(“Tom”, 7.95, 40); System.out.println (p); p = new Manager(“John”, 36000); A super class reference can refer to an object of any subclass

9 The Object Class All classes extend Object, directly or indirectly, explicitly or implicitly, and therefore inherit its methods

10 Methods of Object String toString() boolean equals (Object other)
int hashCode() Object clone() Class getClass() Redefine a method if the default definition is not appropriate for a class that you define Methods toString() and equals() are most useful Good idea to override them in your classes

11 Overriding the toString Method
Object.toString prints class name and the hash code of the object: BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to something like

12 Overriding the toString Method
To provide a nicer representation of an object, override toString: public String toString() { return "BankAccount[balance=" + balance + "]"; } This works better: BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to "BankAccount[balance=5000]"

13 Overriding the equals Method
equals tests for same contents: if (coin1.equals(coin2)) . . . // Contents are the same

14 Overriding the equals Method
== tests for references to the same object: if (coin1 == (coin2)) . . . // Objects are the same

15 Overriding the equals Method
Need to override the equals method of the Object class: public class Coin { private String name; private double value; ... public boolean equals(Object otherObject) }

16 Overriding the equals Method
Cannot change parameter type; use a cast instead: public class Coin { ... public boolean equals(Object otherObject) Coin other = (Coin) otherObject; return name.equals(other.name) && value == other.value; } You should also override the hashCode method so that equal objects have the same hash code

17 Inheritance Hierarchies
Often categorize concepts into hierarchies:

18 Multiple Inheritance

19 Inheritance Hierarchies
Example: Different account types: Checking account: No interest Small number of free transactions per month Charges transaction fee for additional transactions Savings account: Earns interest that compounds monthly Superclass: BankAccount Subclasses: CheckingAccount & SavingsAccount

20 Inheritance Hierarchies
Behavior of account classes: All support getBalance method Also support deposit and withdraw methods, but implementation details differ Checking account needs a method deductFees to deduct the monthly fees and to reset the transaction counter Checking account must override deposit and withdraw methods to count the transactions

21 Inheritance Hierarchies

22 BankAccount.java 1 /** 2 A bank account has a balance that can be changed by 3 deposits and withdrawals. 4 */ 5 public class BankAccount 6 { 7 private double balance; 8 9 /** Constructs a bank account with a zero balance. */ public BankAccount() { balance = 0; } 16 /** Constructs a bank account with a given balance. @param initialBalance the initial balance */ public BankAccount(double initialBalance) { balance = initialBalance; }

23 /** Deposits money into the bank account. @param amount the amount to deposit */ public void deposit(double amount) { balance = balance + amount; } 34 /** Withdraws money from the bank account. @param amount the amount to withdraw */ public void withdraw(double amount) { balance = balance - amount; } 43 /** Gets the current balance of the bank account. @return the current balance */ public double getBalance() { return balance; } 52 }

24 SavingsAccount.java 1 /**
1 /** 2 An account that earns interest at a fixed rate. 3 */ 4 public class SavingsAccount extends BankAccount 5 { 6 private double interestRate; 7 8 /** Constructs a bank account with a given interest rate. @param rate the interest rate */ public SavingsAccount(double rate) { interestRate = rate; } 16 /** Adds the earned interest to the account balance. */ public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); } 25 }

25 CheckingAccount.java 1 /**
1 /** 2 A checking account that charges transaction fees. 3 */ 4 public class CheckingAccount extends BankAccount 5 { 6 private static final int FREE_TRANSACTIONS = 3; 7 private static final double TRANSACTION_FEE = 2.0; 8 9 private int transactionCount; 10 /** Constructs a checking account with a given balance. @param initialBalance the initial balance */ public CheckingAccount(double initialBalance) { // Construct superclass super(initialBalance); 19 // Initialize transaction count transactionCount = 0; } 23

26 24 public void deposit(double amount)
{ transactionCount++; // Now add amount to balance super.deposit(amount); } 30 public void withdraw(double amount) { transactionCount++; // Now subtract amount from balance super.withdraw(amount); } 37 /** Deducts the accumulated fees and resets the transaction count. */ public void deductFees() { if (transactionCount > FREE_TRANSACTIONS){ double fees = TRANSACTION_FEE * (transactionCount - FREE_TRANSACTIONS); super.withdraw(fees); } transactionCount = 0; } 51 }

27 AccountTester.java 1 /**
1 /** 2 This program tests the BankAccount class and 3 its subclasses. 4 */ 5 public class AccountTester 6 { 7 public static void main(String[] args) 8 { SavingsAccount momsSavings = new SavingsAccount(0.5); 10 CheckingAccount harrysChecking = new CheckingAccount(100); 12 momsSavings.deposit(10000); 14 momsSavings.transfer(2000, harrysChecking); harrysChecking.withdraw(1500); harrysChecking.withdraw(80); 18 momsSavings.transfer(1000, harrysChecking); harrysChecking.withdraw(400); 21

28 AccountTester.java (cont.)
// Simulate end of month momsSavings.addInterest(); harrysChecking.deductFees(); 25 System.out.println("Mom’s savings balance: " momsSavings.getBalance()); System.out.println("Expected: 7035"); 29 System.out.println("Harry’s checking balance: " harrysChecking.getBalance()); System.out.println("Expected: 1116"); } 34 } Program Run: Mom's savings balance: Expected: Harry's checking balance: Expected: 1116

29 Visibility Private members are inherited by the child class, but cannot be referenced by name However, they may be used indirectly

30 Final Classes and Methods
public final class A { ... // cannot be extended } public class B { final void f () { ... } // cannot be overridden .... Improve security and optimization


Download ppt "Lecture Notes – Inheritance (Ch 9-10)"

Similar presentations


Ads by Google