Download presentation
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
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
3
Cay Horstmann's Bank Account Example
// 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
4
Cay Horstmann's Bank Account Example
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
5
Cay Horstmann's Bank Account Example
// 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; Cay Horstmann's Bank Account Example
6
Cay Horstmann's Bank Account Example
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
7
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
8
Cay Horstmann's Bank Account Example
Inheritance Diagram Object Unlike C++, Java is singly rooted Bank Account Savings Account 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); Cay Horstmann's Bank Account Example
10
Cay Horstmann's Bank Account Example
public static void main(String args[]) { SavingsAccount rainyDay = new SavingsAccount(100,.10); rainyDay.addInterest(); System.out.println(rainyDay.getAccountNumber()); System.out.println(rainyDay.getBalance()); SavingsAccount collegeFund = new SavingsAccount(1000,.10); collegeFund.addInterest(); System.out.println(collegeFund.getAccountNumber()); System.out.println(collegeFund.getBalance()); } Cay Horstmann's Bank Account Example
11
Cay Horstmann's Bank Account Example
Output C:\heinz\90-876\examples\Inherit\BankAccount>java SavingsAccount 121.0 1 1210.0 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); Cay Horstmann's Bank Account Example
13
Converting Between Class Types
Object o = new SavingsAccount(100,.10); Assignment is fine! An Object 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. 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! 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() 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! 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! 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(); 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? 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(); 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? Cay Horstmann's Bank Account Example
23
Cay Horstmann's Bank Account Example
Inheritance Diagram Object Rectangle Bank Account Savings Account Cay Horstmann's Bank Account Example
24
Cay Horstmann's Bank Account Example
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
25
Cay Horstmann's Bank Account Example
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
26
Cay Horstmann's Bank Account Example
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
27
Inheritance Diagram (UML)
Object Rectangle BankAccount SavingsAccount CDAccount Cay Horstmann's Bank Account Example
28
Cay Horstmann's Bank Account Example
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
29
Only accessible within the class
Java Access Control public Interface Access Only accessible within the class private protected “Sort of private” Cay Horstmann's Bank Account Example
30
Class member accessibility
Java Access Control Class member accessibility Yes No 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 Classes are either public or package access Cay Horstmann's Bank Account Example
31
Interfaces and Abstract classes
Cay Horstmann's Bank Account Example
32
Cay Horstmann's Bank Account Example
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
33
Cay Horstmann's Bank Account Example
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
34
Cay Horstmann's Bank Account Example
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? Cay Horstmann's Bank Account Example
35
Cay Horstmann's Bank Account Example
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!! Cay Horstmann's Bank Account Example
36
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
37
Cay Horstmann's Bank Account Example
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
38
Cay Horstmann's Bank Account Example
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
39
Cay Horstmann's Bank Account Example
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
40
Cay Horstmann's Bank Account Example
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
41
Cay Horstmann's Bank Account Example
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
42
Cay Horstmann's Bank Account Example
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 implements interface Account Cay Horstmann's Bank Account Example
43
Cay Horstmann's Bank Account Example
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
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? 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. Cay Horstmann's Bank Account Example
46
Cay Horstmann's Bank Account Example
INTERFACES public interface Comparable { int compareTo(Object other); } public class Student implements Comparable { // this class MUST define compareTo() Automatically public Found in java.lang Cay Horstmann's Bank Account Example
47
Cay Horstmann's Bank Account Example
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
48
Cay Horstmann's Bank Account Example
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
49
Cay Horstmann's Bank Account Example
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 Cay Horstmann's Bank Account Example
50
Cay Horstmann's Bank Account Example
Abstract Classes Consider public class BankAccount { public void deductFees() { …body goes here ? … } : } public class SavingsAccount extends BankAccount{ What should this method do? We silently get the deductFees() method Cay Horstmann's Bank Account Example
51
Cay Horstmann's Bank Account Example
Abstract Classes No body..It’s up to the derived class to complete. 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 } Cay Horstmann's Bank Account Example
52
Cay Horstmann's Bank Account Example
Abstract Classes Abstract void foo(BankAccount s) { make calls on s.deductFees(); } A real object 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
53
Cay Horstmann's Bank Account Example
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
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"); }
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 ClassCastException is thrown when we try to convert the BigInteger pointed to by o to a String.
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.
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"); }
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"); }
59
The Class Object interface BabySitter { void respondFast(); }
class Dad implements BabySitter { public Dad() {} public void respondFast() {}
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()); }
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); }
62
C:\McCarthy\www\JustJava\Examples>java RTTITest
Dad false BabySitter true java.lang.Object
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; } }
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 TestFruit Grams:0 Calories per gram:0
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(); Cay Horstmann's Bank Account Example
66
Cay Horstmann's Bank Account Example
// 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
67
Cay Horstmann's Bank Account Example
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
68
Cay Horstmann's Bank Account Example
TestException.java class BankBalanceException extends Exception { BankBalanceException(String errorMessage) { super(errorMessage); } Cay Horstmann's Bank Account Example
69
Cay Horstmann's Bank Account Example
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
70
Cay Horstmann's Bank Account Example
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
71
Cay Horstmann's Bank Account Example
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
72
Cay Horstmann's Bank Account Example
Handle the exception 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"); Cay Horstmann's Bank Account Example
73
Cay Horstmann's Bank Account Example
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
74
Exceptions in Java Object Throwable Error Exception RunTimeException
Less severe conditions Unrecoverable problems - e.g. Corrupted class file, out of memory Can be handled but rare - These are all unchecked RunTimeException Checked e.g. ClassNotFoundException CloneNotSupportedException Can occur anywhere Unchecked e.g. Null Pointer Exception, ArrayIndexOutOfBounds
75
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
76
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
77
Error is an Unchecked Exception
class BankBalanceException extends Error { BankBalanceException(String errorMessage) { super(errorMessage); } Cay Horstmann's Bank Account Example
78
Cay Horstmann's Bank Account Example
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 need a throws on our method for an unchecked exception. Cay Horstmann's Bank Account Example
79
Cay Horstmann's Bank Account Example
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 throw or catch an unchecked exception. Cay Horstmann's Bank Account Example
80
Cay Horstmann's Bank Account Example
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
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.