Download Chapter 9

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1
Chapter 9: Inheritance and Interfaces
Chapter 9
Inheritance and Interfaces
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
2
Chapter 9: Inheritance and Interfaces
Figure 1
Inheritance Diagram
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
3
Chapter 9: Inheritance and Interfaces
Inheritance
• class SavingsAccount
extends BankAccount
{ new methods
new instance variables
}
• Existing methods are inherited:
SavingsAccount collegeFund
= new SavingsAccount(10);
collegeFund.deposit(500);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
4
Chapter 9: Inheritance and Interfaces
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”
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
5
Chapter 9: Inheritance and Interfaces
Savings Account Class
•
public class SavingsAccount
extends BankAccount
{ public SavingsAccount(double rate)
{ interestRate = rate;
}
public void addInterest()
{ double interest = getBalance()
* interestRate / 100;
deposit(interest);
}
private double interestRate;
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
6
Chapter 9: Inheritance and Interfaces
Figure 2
Layout of a
Subclass Object
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
7
Chapter 9: Inheritance and Interfaces
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 programming
momsChecking.transfer(collegeFund, 100);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
8
Chapter 9: Inheritance and Interfaces
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)
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
9
Chapter 9: Inheritance and Interfaces
Figure 3
Object Variables
of Different
Types Refer to
the Same Object
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
10
Chapter 9: Inheritance and Interfaces
Figure 4
A Part of the Hierarchy of
Ancient Reptiles
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
11
Chapter 9: Inheritance and Interfaces
Figure 5
A Part of the Hierarchy of Swing
User Interface Components
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
12
Chapter 9: Inheritance and Interfaces
Figure 6
Inheritance
Hierarchy for
Bank Account
Classes
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
13
Chapter 9: Inheritance and Interfaces
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
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
14
Chapter 9: Inheritance and Interfaces
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
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
15
Chapter 9: Inheritance and Interfaces
Figure 7
Shadowing Instance
Variables
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
16
Chapter 9: Inheritance and Interfaces
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;
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
17
Chapter 9: Inheritance and Interfaces
Checking Account
•
public void deposit(double amount)
{ transactionCount++;
super.deposit(balance);
}
• Can't call
balance = balance + amount;
Can't access private data
• Can't call
deposit(balance);
That would be ©2000,
a recursive
John Wiley & Sons,call
Inc.
Horstmann/Java Essentials, 2/e
18
Chapter 9: Inheritance and Interfaces
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;
©2000, John Wiley & Sons, Inc.
}
Horstmann/Java Essentials, 2/e
19
Chapter 9: Inheritance and Interfaces
Subclass Construction
• Use super to call the superclass constructor
public CheckingAccount(double
initialBalance)
{ super(initialBalance);
transactionCount = 0;
}
public TimeDepositAccount(double rate,
int maturity)
{ super(rate);
periodsToMaturity = maturity;
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
20
Chapter 9: Inheritance and Interfaces
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
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
21
Chapter 9: Inheritance and Interfaces
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
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
22
Chapter 9: Inheritance and Interfaces
Figure 8
Polymorphism
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
23
Chapter 9: Inheritance and Interfaces
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);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
24
Chapter 9: Inheritance and Interfaces
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
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
25
Chapter 9: Inheritance and Interfaces
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());
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
26
Chapter 9: Inheritance and Interfaces
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 superinterfaces.
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
27
Chapter 9: Inheritance and 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
©2000, John Wiley & Sons, Inc.
• Class must supply
implementation
Horstmann/Java
Essentials, 2/e
28
Chapter 9: Inheritance and Interfaces
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
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
can sort an array
of savings accounts
29
Chapter 9: Inheritance and Interfaces
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()
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
30
Chapter 9: Inheritance and Interfaces
Figure 9
The Object Class Is the Superclass of
Every Java Class
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
31
Chapter 9: Inheritance and Interfaces
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);
prints
a=BankAccount[balance=5000]
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
32
Chapter 9: Inheritance and Interfaces
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;
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
33
Chapter 9: Inheritance and Interfaces
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();
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
34
Chapter 9: Inheritance and Interfaces
Figure 10
Cloning Objects
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
35
Chapter 9: Inheritance and Interfaces
Figure 11
The Object.clone Method Makes a
Shallow Copy
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
Related documents