JustJava3 - Andrew.cmu.edu

Download Report

Transcript JustJava3 - Andrew.cmu.edu

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
1
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
2
// File Name BankAccount.java
public class BankAccount
{
private double balance;
public BankAccount()
{ balance = 0;
}
public BankAccount(double initialBalance)
{ balance = initialBalance;
}
Cay Horstmann's Bank Account
Example
3
public void deposit(double amount)
{ balance = balance + amount;
}
public void withdraw(double amount)
{ balance = balance - amount;
}
public double getBalance()
{ return balance;
}
}
Cay Horstmann's Bank Account
Example
4
// again but let’s add more members
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++;
}
Cay Horstmann's Bank Account
Example
5
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;
}
}
Cay Horstmann's Bank Account
Example
6
A Savings Account “IS A” Bank
Account
public class SavingsAccount extends BankAccount {
// new methods
// new instance variables
// we already have deposit, withdraw, etc.
}
Cay Horstmann's Bank Account
Example
7
Inheritance Diagram
Object
Unlike C++,
Java is singly rooted
Bank Account
Savings Account
Cay Horstmann's Bank Account
Example
8
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);
}
Cay Horstmann's Bank Account
Example
9
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());
}
}
Cay Horstmann's Bank Account
Example
10
Output
C:\heinz\90-876\examples\Inherit\BankAccount>java SavingsAccount
0
121.0
1
1210.0
Cay Horstmann's Bank Account
Example
11
Converting Between Class Types
A SavingsAccount “is a” BankAccount.
A BankAccount “is a” Object.
Is the following legal?
Object o = new SavingsAccount(100,.10);
Cay Horstmann's Bank Account
Example
12
Converting Between Class Types
Object o = new SavingsAccount(100,.10);
Assignment is fine!
Cay Horstmann's Bank Account
Example
An Object
13
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.
Cay Horstmann's Bank Account
Example
14
Converting Between Class Types
Is the following legal?
SavingsAccount s = new SavingsAccount(100,.10);
BankAccount b = s;
Sure!
Cay Horstmann's Bank Account
Example
15
Converting Between Class Types
Is the following legal?
SavingsAccount s = new SavingsAccount(100,.10);
BankAccount b = s;
b.addInterest()
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()
NO!
A BankAccount object has no addInterest method!
Cay Horstmann's Bank Account
Example
17
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!
Cay Horstmann's Bank Account
Example
18
Converting Between Class Types
How about the following?
SavingsAccount s = new SavingsAccount(100,.10);
Object o = s;
((SavingsAccount)o).addInterest();
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();
Sure!
Why?
Are we taking a risk?
Cay Horstmann's Bank Account
Example
20
Converting Between Class Types
How about the following?
SavingsAccount s = new SavingsAccount(100,.10);
Rectangle r = s;
((SavingsAccount)r).addInterest();
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();
No!
Why?
Cay Horstmann's Bank Account
Example
22
Inheritance Diagram
Object
Rectangle
Bank Account
Savings Account
Cay Horstmann's Bank Account
Example
23
Polymorphism
Consider the following static method:
public void static display(BankAccount b) {
System.out.println(“Acct. Number:” + b.getAccountNumber());
System.out.println(“Balance $” + b.getBalance());
}
Cay Horstmann's Bank Account
Example
24
Polymorphism
Consider 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);
}
Cay Horstmann's Bank Account
Example
25
Polymorphism
How 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);
}
Cay Horstmann's Bank Account
Example
26
Inheritance Diagram (UML)
Object
Rectangle
BankAccount
SavingsAccount
Cay Horstmann's Bank Account
Example
CDAccount
27
Polymorphism
Is 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);
}
Cay Horstmann's Bank Account
Example
28
Java Access Control
public
private
protected
Interface Access
Only accessible within the class
“Sort of private”
Cay Horstmann's Bank Account
Example
29
Java Access Control
Class member accessibility
Accessible to
Member Visibility
Public Protected Package
Same class
Class in same package
Subclass indifferent package
Non-subclass different package
Yes
Yes
Yes
Yes
Yes
Yes
Yes
No
Yes
Yes
No
No
Private
Yes
No
No
No
Classes are either public or package access
Cay Horstmann's Bank Account
Example
30
Interfaces and Abstract
classes
Cay Horstmann's Bank Account
Example
31
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?
Cay Horstmann's Bank Account
Example
32
Inheritance
static void foo(BankAccount x) {
x.withdraw(1000);
x.deposit(50.0);
:
:
}
foo() can call those
methods on x that are
provided by the BankAccount
class
Cay Horstmann's Bank Account
Example
33
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
Cay Horstmann's Bank Account
this routine?
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?
SURE!! 35
Cay Horstmann's Bank Account
Example
Inheritance
Often we want to write a method that is able to handle any object
that meets certain requirements.
In the example above, foo() requires that it receive BankAccount
objects. 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 certain
operations will be available. Interfaces take this a step further…
Cay Horstmann's Bank Account
Example
36
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)
Cay Horstmann's Bank Account
Example
37
The BankAccount Again
interface Account {
public double getBalance();
public void setBalance(double x);
}
Any class that implements this
interface MUST have these
two methods defined exactly
as specified.
Cay Horstmann's Bank Account
Example
38
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;
Cay Horstmann's Bank Account
Example
}
39
public void deposit(double amount)
{ balance = balance + amount;
}
public void withdraw(double amount)
{ balance = balance - amount;
}
public double getBalance()
{ return balance;
}
Cay Horstmann's Bank Account
Example
40
public void setBalance(double a) {
balance = a;
}
public void update() {
balance = balance + balance * rate;
}
}
We have provided
implementations for
the two methods.
Cay Horstmann's Bank Account
Example
41
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();
Call foo() with an
}
myAccount.deposit(100); object that implements
interface Account
foo(myAccount);
}
Cay Horstmann's Bank Account
Example
42
public static void foo(Account a) {
double m = a.getBalance();
System.out.println(m);
The name of
an interface
}
}
Any other class that implements Account can
be passed to foo().
Cay Horstmann's Bank Account
Example
43
Consider A Student Class
public class Student {
How would
you put
these three
}
in order?
Student x = new Student(“Joe”,2.3);
Student y = new Student(“Zack”,1.7);
Student z = new Student(“Amy”,3.0);
Cay Horstmann's Bank Account
Example
44
Consider A Student Class
public class Student {
It depends
on how
they are
}
compared.
Student x = new Student(“Joe”,2.3);
Student y = new Student(“Zack”,3.7);
Student z = new Student(“Amy”,3.0);
Cay Horstmann's Bank Account
Example
45
INTERFACES
Automatically public
Found in java.lang
public interface Comparable {
int compareTo(Object other);
}
public class Student implements Comparable {
// this class MUST define compareTo()
}
Cay Horstmann's Bank Account
Example
46
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?
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? SURE
Why would we want to? Perhaps foo() sorts.
Cay Horstmann's Bank Account
Example
48
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
Cay Horstmann's Bank Account
49
the method
Example
Abstract Classes
• Consider
What should this method do?
public class BankAccount {
public void deductFees() { …body goes here ? … }
:
:
We silently get the
}
deductFees() method
public class SavingsAccount extends BankAccount{
}
Cay Horstmann's Bank Account
Example
50
Abstract Classes
• Writing an Abstract class
No body..It’s up to the
derived class to complete.
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 }
Cay Horstmann's Bank Account
51
}
Example
Abstract Classes
Abstract
void foo(BankAccount s) {
A real object
make calls on s.deductFees(); at run time.
}
Many classes can extend the abstract class,
get some code reuse, but are forced to define
the abstract method deductFees() .
Cay Horstmann's Bank Account
Example
52
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
Cay Horstmann's Bank Account
Example
53
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");
}
54
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 ClassCastException
is thrown when we try to convert the BigInteger
pointed to by o to a String.
55
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.
56
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");
}
}
57
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");
}
}
58
The Class Object
interface BabySitter {
void respondFast();
}
class Dad implements BabySitter {
public Dad() {}
public void respondFast() {}
}
59
public class RTTITest {
public static void displayInfo(Class c) {
System.out.println(c.getName());
System.out.println(c.isInterface());
System.out.println(c.isArray());
}
60
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);
}
}
61
C:\McCarthy\www\JustJava\Examples>java RTTITest
Dad
false
false
BabySitter
true
false
BabySitter
true
false
java.lang.Object
false
false
62
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; }
}
63
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 TestFruit
Grams:0 Calories per gram:0
64
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();
Cay Horstmann's Bank Account
Example
65
// 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);
}
}
Cay Horstmann's Bank Account
Example
66
C:\McCarthy\www\JustJava\Examples>java TestFruit
Fruit extends
java.lang.Object extends
Grams:0 Calories per gram:0
Cay Horstmann's Bank Account
Example
67
TestException.java
class BankBalanceException extends Exception {
BankBalanceException(String errorMessage) {
super(errorMessage);
}
}
Cay Horstmann's Bank Account
Example
68
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;
}
Cay Horstmann's Bank Account
Example
69
public void deposit(double amount)
{ balance = balance + amount;
}
public void withdraw(double amount)
{ balance = balance - amount;
}
public double getBalance()
{ return balance;
}
}
Cay Horstmann's Bank Account
Example
70
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 must
be caught, or it must
be declared in the throws clause of this method.
BankAccount billG = new BankAccount(100.0);
^
1 error
Cay Horstmann's Bank Account
Example
71
public class TestException {
Handle the exception
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");
}
}
Cay Horstmann's Bank Account
Example
72
C:\McCarthy\www\95-713\examples>java TestException
Balance initialized too low
BankBalanceException: balance less than 0
Exiting
End of program
Cay Horstmann's Bank Account
Example
73
Exceptions in Java
Object
Throwable
Error
Exception
Less severe conditions
Unrecoverable problems
- e.g. Corrupted class file, out
of memory
RunTimeException Checked
-Can be handled but rare
e.g.
Can occur anywhere
-- These are all unchecked
ClassNotFoundException
Unchecked
74
e.g. Null Pointer Exception, CloneNotSupportedExceptio
ArrayIndexOutOfBounds
Exceptions
Checked Exceptions must be explicitly thrown or handled. The compiler
will enforce this rule.
Unchecked exceptions, for example ArrayIndexOutOfBounds, need
not 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
Java in a Nutshell
75
Exceptions
try {
// 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()
}
Java in a Nutshell
76
Error is an Unchecked Exception
class BankBalanceException extends Error {
BankBalanceException(String errorMessage) {
super(errorMessage);
}
}
Cay Horstmann's Bank Account
Example
77
class BankAccount
{
private double balance;
public BankAccount()
{ balance = 0;
}
We don’t need
a throws
on our method
for an
unchecked
exception.
public BankAccount(double initialBalance)
{
if (initialBalance < 0) throw new
BankBalanceException("balance less than 0");
balance = initialBalance;
}
public void deposit(double amount)
{ balance = balance
+ amount;
Cay Horstmann's Bank Account
78
Example
}
public void withdraw(double amount)
{ balance = balance - amount;
}
public double getBalance()
{ return balance;
}
}
public class TestException {
We don’t
have to throw
or catch an
unchecked
exception.
public static void main(String a[]) {
BankAccount billG = new BankAccount(100.0);
BankAccount mikeM = new BankAccount(-230.0);
}
}
Cay Horstmann's Bank Account
Example
79
C:\McCarthy\www\95-713\examples>javac TestException.java
C:\McCarthy\www\95-713\examples>java TestException
Exception in thread "main" BankBalanceException:
balance less than 0
at BankAccount.<init>(TestException.java:18)
at TestException.main(TestException.java:39)
Cay Horstmann's Bank Account
Example
80