1 lecture 3 “just java” chapter 6 - inheritance, polymorphism and the class whose name is class...
Post on 19-Dec-2015
222 views
TRANSCRIPT
![Page 1: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/1.jpg)
Cay Horstmann's Bank Account Example
1
Lecture 3
“Just Java” Chapter 6 - Inheritance,Polymorphism and the class whose name is Class“Just Java” Chapter 7 Exceptions
BankAccount example is from Cay Horstmann’s “Java 2 Essentials” Chapter 9
![Page 2: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/2.jpg)
Cay Horstmann's Bank Account Example
2
Important Programming Concepts
• Inheritance and code reuse
• Supertype• Base Class• Subtype• Derived Class• The Extends keyword• The “is a” relationship
• Inheritance Diagram• The Object class• Converting Between
Class Types• Polymorphism• RTTI• Exceptions
![Page 3: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/3.jpg)
Cay Horstmann's Bank Account Example
3
// File Name BankAccount.java
public class BankAccount{ private double balance;
public BankAccount() { balance = 0; }
public BankAccount(double initialBalance) { balance = initialBalance; }
![Page 4: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/4.jpg)
Cay Horstmann's Bank Account Example
4
public void deposit(double amount) { balance = balance + amount; }
public void withdraw(double amount) { balance = balance - amount; }
public double getBalance() { return balance; }
}
![Page 5: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/5.jpg)
Cay Horstmann's Bank Account Example
5
class BankAccount {
static private int accountNumber = 0; private double balance; private int acctNum; public BankAccount() { balance = 0; acctNum = accountNumber++; } public BankAccount(double initialBalance) { balance = initialBalance; acctNum = accountNumber++; }
// again but let’s add more members
![Page 6: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/6.jpg)
Cay Horstmann's Bank Account Example
6
public void deposit(double amount) { balance = balance + amount;}public void withdraw(double amount) { balance = balance - amount;}public int getAccountNumber() { return acctNum;}public double getBalance() { return balance;}
}
![Page 7: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/7.jpg)
Cay Horstmann's Bank Account Example
7
A Savings Account “IS A” Bank Account
public class SavingsAccount extends BankAccount { // new methods // new instance variables // we already have deposit, withdraw, etc.
}
![Page 8: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/8.jpg)
Cay Horstmann's Bank Account Example
8
Inheritance Diagram
Object
Bank Account
Savings Account
Unlike C++,Java is singly rooted
![Page 9: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/9.jpg)
Cay Horstmann's Bank Account Example
9
Specializing the base class
class SavingsAccount extends BankAccount {
private double rate;
public SavingsAccount(double initialDeposit, double interestRate) { super(initialDeposit); rate = interestRate; }
void addInterest() { double interest = getBalance() * rate; deposit(interest); }
![Page 10: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/10.jpg)
Cay Horstmann's Bank Account Example
10
public static void main(String args[]) { SavingsAccount rainyDay = new SavingsAccount(100,.10); rainyDay.addInterest(); rainyDay.addInterest(); System.out.println(rainyDay.getAccountNumber()); System.out.println(rainyDay.getBalance());
SavingsAccount collegeFund = new SavingsAccount(1000,.10); collegeFund.addInterest(); collegeFund.addInterest(); System.out.println(collegeFund.getAccountNumber()); System.out.println(collegeFund.getBalance()); }}
![Page 11: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/11.jpg)
Cay Horstmann's Bank Account Example
11
Output
C:\heinz\90-876\examples\Inherit\BankAccount>java SavingsAccount0121.011210.0
![Page 12: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/12.jpg)
Cay Horstmann's Bank Account Example
12
Converting Between Class Types
A SavingsAccount “is a” BankAccount.
A BankAccount “is a” Object.
Is the following legal?
Object o = new SavingsAccount(100,.10);
![Page 13: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/13.jpg)
Cay Horstmann's Bank Account Example
13
Converting Between Class Types
Object o = new SavingsAccount(100,.10);
An ObjectAssignment is fine!
![Page 14: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/14.jpg)
Cay Horstmann's Bank Account Example
14
Converting Between Class Types
Is the following legal?
SavingsAccount s = new SavingsAccount(100,.10); Object o = s;
Sure!
Both references point to the same object.
![Page 15: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/15.jpg)
Cay Horstmann's Bank Account Example
15
Converting Between Class Types
Is the following legal?
SavingsAccount s = new SavingsAccount(100,.10); BankAccount b = s;
Sure!
![Page 16: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/16.jpg)
Cay Horstmann's Bank Account Example
16
Converting Between Class Types
Is the following legal?
SavingsAccount s = new SavingsAccount(100,.10); BankAccount b = s; b.addInterest()
![Page 17: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/17.jpg)
Cay Horstmann's Bank Account Example
17
Converting Between Class Types
Is the following legal?
SavingsAccount s = new SavingsAccount(100,.10); BankAccount b = s; b.addInterest()
NO!
A BankAccount object has no addInterest method!
![Page 18: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/18.jpg)
Cay Horstmann's Bank Account Example
18
Converting Between Class Types
Is the following legal?
SavingsAccount s = new SavingsAccount(100,.10); BankAccount b = s; ((SavingsAccount)b).addInterest();
Yes!
We tell the compiler we will take the risk!
![Page 19: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/19.jpg)
Cay Horstmann's Bank Account Example
19
Converting Between Class Types
How about the following?
SavingsAccount s = new SavingsAccount(100,.10); Object o = s; ((SavingsAccount)o).addInterest();
![Page 20: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/20.jpg)
Cay Horstmann's Bank Account Example
20
Converting Between Class Types
How about the following?
SavingsAccount s = new SavingsAccount(100,.10); Object o = s; ((SavingsAccount)o).addInterest();
Sure!
Why?
Are we taking a risk?
![Page 21: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/21.jpg)
Cay Horstmann's Bank Account Example
21
Converting Between Class Types
How about the following?
SavingsAccount s = new SavingsAccount(100,.10); Rectangle r = s; ((SavingsAccount)r).addInterest();
![Page 22: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/22.jpg)
Cay Horstmann's Bank Account Example
22
Converting Between Class Types
How about the following?
SavingsAccount s = new SavingsAccount(100,.10); Rectangle r = s; ((SavingsAccount)r).addInterest();
No!
Why?
![Page 23: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/23.jpg)
Cay Horstmann's Bank Account Example
23
Inheritance Diagram
Object
Bank Account
Savings Account
Rectangle
![Page 24: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/24.jpg)
Cay Horstmann's Bank Account Example
24
PolymorphismConsider the following static method:
public void static display(BankAccount b) { System.out.println(“Acct. Number:” + b.getAccountNumber()); System.out.println(“Balance $” + b.getBalance());}
![Page 25: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/25.jpg)
Cay Horstmann's Bank Account Example
25
PolymorphismConsider the following static method:
public void static display(BankAccount b) { System.out.println(“Acct. Number:” + b.getAccountNumber()); System.out.println(“Balance $” + b.getBalance());}
// Suppose we call it with the following code. What happens?public static void main(String args[]) {
BankAccount collegeFund = new BankAccount(100); display(collegeFund);}
![Page 26: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/26.jpg)
Cay Horstmann's Bank Account Example
26
PolymorphismHow about with this code?
public void static display(BankAccount b) { System.out.println(“Acct. Number:” + b.getAccountNumber()); System.out.println(“Balance $” + b.getBalance());}
public static void main(String args[]) {
SavingsAccount rainyDay = new SavingsAccount(100,.10); display(rainyDay);}
![Page 27: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/27.jpg)
Cay Horstmann's Bank Account Example
27
Inheritance Diagram (UML)
Object
BankAccount
SavingsAccount
Rectangle
CDAccount
![Page 28: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/28.jpg)
Cay Horstmann's Bank Account Example
28
PolymorphismIs this OK?
public void static display(BankAccount b) { System.out.println(“Acct. Number:” + b.getAccountNumber()); System.out.println(“Balance $” + b.getBalance());}
public static void main(String args[]) {
CDAccount retirement= new CDAccount(100,.10,5); display(retirement);}
![Page 29: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/29.jpg)
Cay Horstmann's Bank Account Example
29
Java Access Control
public Interface Access
private
protected
Only accessible within the class
“Sort of private”
![Page 30: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/30.jpg)
Cay Horstmann's Bank Account Example
30
Class member accessibility
Yes
No
No
No
Yes Yes Yes
Yes Yes Yes
Yes Yes No
Yes No No
Same class
Class in same package
Subclass indifferent package
Non-subclass different package
Private
Member Visibility
Public Protected Package
Accessible to
Java Access Control
Classes are either public or package access
![Page 31: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/31.jpg)
Cay Horstmann's Bank Account Example
31
Interfaces and Abstract classes
![Page 32: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/32.jpg)
Cay Horstmann's Bank Account Example
32
Review Inheritance
• The inheritance relationship is often called the “is-a” relationship.• For example, a CheckingAccount “is-a” BankAccount.• Now, suppose that we have a routine that manipulates BankAccount objects --
static void foo(BankAccount x) { // do things to x }
• What kind of things can foo() do to x?
![Page 33: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/33.jpg)
Cay Horstmann's Bank Account Example
33
Inheritance
static void foo(BankAccount x) { x.withdraw(1000); x.deposit(50.0); : : } foo() can call those
methods on x that areprovided by the BankAccountclass
![Page 34: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/34.jpg)
Cay Horstmann's Bank Account Example
34
Inheritance
// A CheckingAccount “is-a” BankAccount.
class CheckingAccount extends BankAccount {
}
static void foo(BankAccount x) { // do things to x }
Should we be able to pass a CheckingAccount object to this routine?
![Page 35: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/35.jpg)
Cay Horstmann's Bank Account Example
35
Inheritance
// A CheckingAccount “is-a” BankAccount.
class CheckingAccount extends BankAccount {
}
static void foo(BankAccount x) { // do things to x } Should we be able to pass a CheckingAccount object to this routine?
SURE!!
![Page 36: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/36.jpg)
Cay Horstmann's Bank Account Example
36
Inheritance
Often we want to write a method that is able to handle any objectthat meets certain requirements.
In the example above, foo() requires that it receive BankAccountobjects. The objects may be CD Account objects or Checking Account objects etc.. As long as the object that is passed to foo() extends the BankAccount class, the writer of foo() knows that the object has methods called “deposit” and “withdraw”.
Since the object “is a” BankAccount, we are promised that certainoperations will be available. Interfaces take this a step further…
![Page 37: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/37.jpg)
Cay Horstmann's Bank Account Example
37
INTERFACES
• Interfaces
• Replace multiple inheritance• Have no instance variables• Have only abstract methods (all parameters but no bodies)• Have only public methods• Are implemented not extended as in inheritance• Are not classes…you can’t create interface objects• May be referenced• May contain constants (all are public static final by default)
![Page 38: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/38.jpg)
Cay Horstmann's Bank Account Example
38
The BankAccount Again
interface Account { public double getBalance(); public void setBalance(double x);}
Any class that implements thisinterface MUST have thesetwo methods defined exactly as specified.
![Page 39: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/39.jpg)
Cay Horstmann's Bank Account Example
39
class BankAccount implements Account { private double balance; private double rate;
public BankAccount() { balance = 0; } public BankAccount(double initialBalance, double arate) { rate = arate / 100;; balance = initialBalance; }
![Page 40: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/40.jpg)
Cay Horstmann's Bank Account Example
40
public void deposit(double amount) { balance = balance + amount; }
public void withdraw(double amount) { balance = balance - amount; }
public double getBalance() { return balance; }
![Page 41: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/41.jpg)
Cay Horstmann's Bank Account Example
41
public void setBalance(double a) { balance = a; } public void update() { balance = balance + balance * rate; }}
We have providedimplementations forthe two methods.
![Page 42: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/42.jpg)
Cay Horstmann's Bank Account Example
42
public class BankAccountTest{ public static void main(String[] args) { BankAccount myAccount = new BankAccount(1000,10); int month; for (month = 1; month <= 2; month++) { myAccount.update(); } myAccount.deposit(100); foo(myAccount); }
Call foo() with an object that implementsinterface Account
![Page 43: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/43.jpg)
Cay Horstmann's Bank Account Example
43
public static void foo(Account a) {
double m = a.getBalance(); System.out.println(m); } }
The name ofan interface
Any other class that implements Account canbe passed to foo().
![Page 44: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/44.jpg)
Cay Horstmann's Bank Account Example
44
Consider A Student Class
public class Student {
}
Student x = new Student(“Joe”,2.3);
Student y = new Student(“Zack”,1.7);
Student z = new Student(“Amy”,3.0);
How would you put these three in order?
![Page 45: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/45.jpg)
Cay Horstmann's Bank Account Example
45
Consider A Student Class
public class Student {
}
Student x = new Student(“Joe”,2.3);
Student y = new Student(“Zack”,3.7);
Student z = new Student(“Amy”,3.0);
It depends on how they are compared.
![Page 46: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/46.jpg)
Cay Horstmann's Bank Account Example
46
INTERFACES
public interface Comparable { int compareTo(Object other); }
public class Student implements Comparable { // this class MUST define compareTo() }
Automatically public
Found in java.lang
![Page 47: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/47.jpg)
Cay Horstmann's Bank Account Example
47
INTERFACES
Suppose we have a function foo
void foo(Comparable x[]) {
}
Can we pass an array of Student objects to this function? Why would we want to?
![Page 48: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/48.jpg)
Cay Horstmann's Bank Account Example
48
INTERFACES
Suppose we have a function foo
void foo(Comparable x[]) {
}
Can we pass an array of Student objects to this function? SURE Why would we want to? Perhaps foo() sorts.
![Page 49: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/49.jpg)
Cay Horstmann's Bank Account Example
49
Abstract Classes
• When you extend an existing class, you have a choice whether or not to redefine the methods of the superclass. If you don’t redefine the method, it will appear in the derived class as it appears in the superclass.
• Sometimes it is desirable to force derived class programmers to redefine a method
• There may be no good (superclass) default for the method
• Only the subclass programmer can know how to implement the method
![Page 50: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/50.jpg)
Cay Horstmann's Bank Account Example
50
Abstract Classes
• Consider
public class BankAccount { public void deductFees() { …body goes here ? … } : : }
public class SavingsAccount extends BankAccount{
}
We silently get the deductFees() method
What should this method do?
![Page 51: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/51.jpg)
Cay Horstmann's Bank Account Example
51
Abstract Classes
• Writing an Abstract class
public abstract class BankAccount { public abstract void deductFees(); public double getBalance() { return balance; } : }
public class SavingsAccount extends BankAccount{ public void deductFees() { // deduct fees according to // the account type } }
No body..It’s up to thederived class to complete.
![Page 52: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/52.jpg)
Cay Horstmann's Bank Account Example
52
Abstract Classes
void foo(BankAccount s) {
make calls on s.deductFees();}
Abstract
A real objectat run time.
Many classes can extend the abstract class,get some code reuse, but are forced to definethe abstract method deductFees() .
![Page 53: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/53.jpg)
Cay Horstmann's Bank Account Example
53
Abstract Classes
• An abstract method has no implementation•You can’t construct objects of classes with abstract methods• You can only create objects of concrete classes• The class must be declared with the keyword abstract• It’s fine to have handles that reference abstract classes• Abstract classes, unlike interfaces, may have concrete methods and instance variables
![Page 54: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/54.jpg)
Cay Horstmann's Bank Account Example
54
RTTI Run-Time Type Identification
If we have a reference to an object’s base type we can find out the exact type of the object.
public static void foo(Object o) {
if(o instanceof Fruit) System.out.println("Found a Fruit"); if(o instanceof BigInteger) System.out.println("Found a Big Int"); }
![Page 55: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/55.jpg)
Cay Horstmann's Bank Account Example
55
Some type checking is automatic
Object o = new BigInteger("1234");BigInteger x = (BigInteger)o;String st = (String)o;
All casts are checked at run time. A ClassCastExceptionis thrown when we try to convert the BigInteger pointed to by o to a String.
![Page 56: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/56.jpg)
Cay Horstmann's Bank Account Example
56
But we have access to The Class Object
• There is a Class object for each class in your program.
• The Class object for a particular class holds information about that class.
• It will be loaded at run time if not already in the JVM.
• A Java program is not completely loaded before it starts.
• The Class object is of class Class.
![Page 57: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/57.jpg)
Cay Horstmann's Bank Account Example
57
instanceof and isInstanceOf
// Given an object, check its type:
public class ShortTest {
public static void main(String args[]) {
Object o = new Fruit(); if(o instanceof Fruit) System.out.println("it's a Fruit"); } }
![Page 58: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/58.jpg)
Cay Horstmann's Bank Account Example
58
instanceof and isInstanceOf // Given a type, check an object
public class ShortTest {
public static void main(String args[]) {
Object o = new Fruit(); Class c = o.getClass();
if(c.isInstance(o)) System.out.println("it's a Fruit"); } }
![Page 59: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/59.jpg)
Cay Horstmann's Bank Account Example
59
The Class Object
interface BabySitter {
void respondFast();}class Dad implements BabySitter {
public Dad() {} public void respondFast() {}}
![Page 60: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/60.jpg)
Cay Horstmann's Bank Account Example
60
public class RTTITest {
public static void displayInfo(Class c) { System.out.println(c.getName()); System.out.println(c.isInterface()); System.out.println(c.isArray()); }
![Page 61: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/61.jpg)
Cay Horstmann's Bank Account Example
61
public static void main(String args[]) throws Exception { Class a = Class.forName("Dad"); // name could be entered at run // time. Dad is on the classpath. displayInfo(a); Class b = Class.forName("BabySitter"); displayInfo(b);
Class[] faces = a.getInterfaces(); for(int i = 0; i < faces.length; i++) displayInfo(faces[i]); Class sup = a.getSuperclass(); displayInfo(sup); }}
![Page 62: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/62.jpg)
Cay Horstmann's Bank Account Example
62
C:\McCarthy\www\JustJava\Examples>java RTTITestDadfalsefalseBabySittertruefalseBabySittertruefalsejava.lang.Objectfalsefalse
![Page 63: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/63.jpg)
Cay Horstmann's Bank Account Example
63
Creating an Object from a Name
public class Fruit { private int grams; private int calsPerGram; public Fruit() { this(0,0); } public Fruit(int g, int c) { grams = g; calsPerGram = c; } public String toString() { return "Grams:" + grams + " Calories per gram:" + calsPerGram; }}
![Page 64: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/64.jpg)
Cay Horstmann's Bank Account Example
64
public class TestFruit {
public static void main(String a[]) throws Exception {
String any = "Fruit"; // The compiler has no idea what class // we will be working with Object m = Class.forName(any).newInstance(); System.out.println(m); } }
C:\McCarthy\www\JustJava\Examples>java TestFruitGrams:0 Calories per gram:0
![Page 65: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/65.jpg)
Cay Horstmann's Bank Account Example
65
It gets more interesting
// Sample code modified from "Java in a Nutshell"
import java.lang.reflect.*;public class TestFruit {
public static void main(String a[]) throws Exception {
String any = "Fruit"; // any class in the classpath // build an object of that class Object o = Class.forName(any).newInstance();
// get the Class object Class c = o.getClass();
![Page 66: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/66.jpg)
Cay Horstmann's Bank Account Example
66
// if it's an array figure out its base type while(c.isArray()) c = c.getComponentType();
// if c is not primitive then print its class hierarchy if(!c.isPrimitive()) { for(Class s = c; s != null; s = s.getSuperclass()) System.out.println(s.getName() + " extends"); }
// get a toString() method from the class passing an empty // array of arg types Method m = c.getMethod("toString", new Class[] {} ); // Call the method pointed to by m // include the calling instance and, in this case, an empty array // of parameters String s = (String) m.invoke(o, new Object[] {}); System.out.println(s); } }
![Page 67: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/67.jpg)
Cay Horstmann's Bank Account Example
67
C:\McCarthy\www\JustJava\Examples>java TestFruitFruit extendsjava.lang.Object extendsGrams:0 Calories per gram:0
![Page 68: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/68.jpg)
Cay Horstmann's Bank Account Example
68
TestException.javaclass BankBalanceException extends Exception {
BankBalanceException(String errorMessage) { super(errorMessage); }}
![Page 69: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/69.jpg)
Cay Horstmann's Bank Account Example
69
class BankAccount{ private double balance;
public BankAccount() { balance = 0; }
public BankAccount(double initialBalance) throws BankBalanceException { if (initialBalance < 0) throw new BankBalanceException("balance less than 0"); balance = initialBalance; }
![Page 70: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/70.jpg)
Cay Horstmann's Bank Account Example
70
public void deposit(double amount) { balance = balance + amount; }
public void withdraw(double amount) { balance = balance - amount; }
public double getBalance() { return balance; }}
![Page 71: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/71.jpg)
Cay Horstmann's Bank Account Example
71
public class TestException {
public static void main(String a[]) {
BankAccount billG = new BankAccount(100.0); BankAccount mikeM = new BankAccount(-230.0); }}
C:\McCarthy\www\95-713\examples>javac TestException.java
TestException.java:38: Exception BankBalanceException mustbe caught, or it must be declared in the throws clause of this method. BankAccount billG = new BankAccount(100.0); ^1 error
![Page 72: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/72.jpg)
Cay Horstmann's Bank Account Example
72
public class TestException {
public static void main(String a[]) { try { BankAccount billG = new BankAccount(100.0); BankAccount mikeM = new BankAccount(-230.0); } catch(BankBalanceException e) { System.out.println("Balance initialized too low"); System.out.println(e); } finally { System.out.println("Exiting"); } System.out.println("End of program"); }}
Handle the exception
![Page 73: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/73.jpg)
Cay Horstmann's Bank Account Example
73
C:\McCarthy\www\95-713\examples>java TestExceptionBalance initialized too lowBankBalanceException: balance less than 0ExitingEnd of program
![Page 74: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/74.jpg)
Cay Horstmann's Bank Account Example
74
Exceptions in Java
Object
Throwable
Error ExceptionUnrecoverable problems- e.g. Corrupted class file, out of memory-Can be handled but rare-- These are all unchecked
Less severe conditions
RunTimeExceptionCan occur anywhereUncheckede.g. Null Pointer Exception,ArrayIndexOutOfBounds
Checkede.g. ClassNotFoundExceptionCloneNotSupportedException
![Page 75: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/75.jpg)
Java in a Nutshell 75
ExceptionsChecked Exceptions must be explicitly thrown or handled. The compilerwill enforce this rule.
Unchecked exceptions, for example ArrayIndexOutOfBounds, neednot be caught or explicitly throw but may be.
When a throw is executed:
jump to the handler in current block if no handler exists then check next higher enclosing block and so on… if no handler exists in the method then jump to the calling statement and look for a handler in that code if this goes back to main and there is no handler then stop the interpreter and print the error with a stack trace
![Page 76: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/76.jpg)
Java in a Nutshell 76
Exceptionstry { // exception x thrown here }catch(SomeThrowableClass e) { // The first catch clause that matches x runs // x caught here if x is a class or a subclass of e}catch(SomeOtherThrowableClass e) {
} finally { // this code runs unless the try performed System.exit()}
![Page 77: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/77.jpg)
Cay Horstmann's Bank Account Example
77
Error is an Unchecked Exception
class BankBalanceException extends Error {
BankBalanceException(String errorMessage) { super(errorMessage); }}
![Page 78: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/78.jpg)
Cay Horstmann's Bank Account Example
78
class BankAccount{ private double balance;
public BankAccount() { balance = 0; }
public BankAccount(double initialBalance) { if (initialBalance < 0) throw new BankBalanceException("balance less than 0"); balance = initialBalance; } public void deposit(double amount) { balance = balance + amount; }
We don’t needa throwson our methodfor an unchecked exception.
![Page 79: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/79.jpg)
Cay Horstmann's Bank Account Example
79
public void withdraw(double amount) { balance = balance - amount; }
public double getBalance() { return balance; }}
public class TestException {
public static void main(String a[]) { BankAccount billG = new BankAccount(100.0); BankAccount mikeM = new BankAccount(-230.0); }}
We don’t have to throwor catch an unchecked exception.
![Page 80: 1 Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions BankAccount example is](https://reader036.vdocuments.us/reader036/viewer/2022081514/56649d3a5503460f94a140ad/html5/thumbnails/80.jpg)
Cay Horstmann's Bank Account Example
80
C:\McCarthy\www\95-713\examples>javac TestException.java
C:\McCarthy\www\95-713\examples>java TestExceptionException in thread "main" BankBalanceException: balance less than 0 at BankAccount.<init>(TestException.java:18) at TestException.main(TestException.java:39)