Lecture 3 Just Java Chapter 6 Inheritance Polymorphism









![public static void main(String args[]) { Savings. Account rainy. Day = new Savings. Account(100, public static void main(String args[]) { Savings. Account rainy. Day = new Savings. Account(100,](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-10.jpg)































![public class Bank. Account. Test { public static void main(String[] args) { Bank. Account public class Bank. Account. Test { public static void main(String[] args) { Bank. Account](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-42.jpg)




![INTERFACES Suppose we have a function foo void foo(Comparable x[]) { } Can we INTERFACES Suppose we have a function foo void foo(Comparable x[]) { } Can we](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-47.jpg)
![INTERFACES Suppose we have a function foo void foo(Comparable x[]) { } Can we INTERFACES Suppose we have a function foo void foo(Comparable x[]) { } Can we](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-48.jpg)












![public static void main(String args[]) throws Exception { Class a = Class. for. Name("Dad"); public static void main(String args[]) throws Exception { Class a = Class. for. Name("Dad");](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-61.jpg)


![public class Test. Fruit { public static void main(String a[]) throws Exception { String public class Test. Fruit { public static void main(String a[]) throws Exception { String](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-64.jpg)






![public class Test. Exception { public static void main(String a[]) { Bank. Account bill. public class Test. Exception { public static void main(String a[]) { Bank. Account bill.](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-71.jpg)
![public class Test. Exception { Handle the exception public static void main(String a[]) { public class Test. Exception { Handle the exception public static void main(String a[]) {](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-72.jpg)








- Slides: 80

Lecture 3 “Just Java” Chapter 6 - Inheritance, Polymorphism and the class whose name is Class “Just Java” Chapter 7 Exceptions Bank. Account 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 Bank. Account. java public class Bank. Account { private double balance; public Bank. Account() { balance = 0; } public Bank. Account(double initial. Balance) { balance = initial. Balance; } 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 get. Balance() { return balance; } } Cay Horstmann's Bank Account Example 4

// again but let’s add more members class Bank. Account { static private int account. Number = 0; private double balance; private int acct. Num; public Bank. Account() { balance = 0; acct. Num = account. Number++; } public Bank. Account(double initial. Balance) { balance = initial. Balance; acct. Num = account. Number++; } 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 get. Account. Number() { return acct. Num; } public double get. Balance() { return balance; } } Cay Horstmann's Bank Account Example 6

A Savings Account “IS A” Bank Account public class Savings. Account extends Bank. Account { // 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 Savings. Account extends Bank. Account { private double rate; public Savings. Account(double initial. Deposit, double interest. Rate) { super(initial. Deposit); rate = interest. Rate; } void add. Interest() { double interest = get. Balance() * rate; deposit(interest); } Cay Horstmann's Bank Account Example 9
![public static void mainString args Savings Account rainy Day new Savings Account100 public static void main(String args[]) { Savings. Account rainy. Day = new Savings. Account(100,](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-10.jpg)
public static void main(String args[]) { Savings. Account rainy. Day = new Savings. Account(100, . 10); rainy. Day. add. Interest(); System. out. println(rainy. Day. get. Account. Number()); System. out. println(rainy. Day. get. Balance()); Savings. Account college. Fund = new Savings. Account(1000, . 10); college. Fund. add. Interest(); System. out. println(college. Fund. get. Account. Number()); System. out. println(college. Fund. get. Balance()); } } Cay Horstmann's Bank Account Example 10

Output C: heinz90 -876examplesInheritBank. Account>java Savings. Account 0 121. 0 1 1210. 0 Cay Horstmann's Bank Account Example 11

Converting Between Class Types A Savings. Account “is a” Bank. Account. A Bank. Account “is a” Object. Is the following legal? Object o = new Savings. Account(100, . 10); Cay Horstmann's Bank Account Example 12

Converting Between Class Types Object o = new Savings. Account(100, . 10); Assignment is fine! Cay Horstmann's Bank Account Example An Object 13

Converting Between Class Types Is the following legal? Savings. Account s = new Savings. Account(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? Savings. Account s = new Savings. Account(100, . 10); Bank. Account b = s; Sure! Cay Horstmann's Bank Account Example 15

Converting Between Class Types Is the following legal? Savings. Account s = new Savings. Account(100, . 10); Bank. Account b = s; b. add. Interest() Cay Horstmann's Bank Account Example 16

Converting Between Class Types Is the following legal? Savings. Account s = new Savings. Account(100, . 10); Bank. Account b = s; b. add. Interest() NO! A Bank. Account object has no add. Interest method! Cay Horstmann's Bank Account Example 17

Converting Between Class Types Is the following legal? Savings. Account s = new Savings. Account(100, . 10); Bank. Account b = s; ((Savings. Account)b). add. Interest(); 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? Savings. Account s = new Savings. Account(100, . 10); Object o = s; ((Savings. Account)o). add. Interest(); Cay Horstmann's Bank Account Example 19

Converting Between Class Types How about the following? Savings. Account s = new Savings. Account(100, . 10); Object o = s; ((Savings. Account)o). add. Interest(); Sure! Why? Are we taking a risk? Cay Horstmann's Bank Account Example 20

Converting Between Class Types How about the following? Savings. Account s = new Savings. Account(100, . 10); Rectangle r = s; ((Savings. Account)r). add. Interest(); Cay Horstmann's Bank Account Example 21

Converting Between Class Types How about the following? Savings. Account s = new Savings. Account(100, . 10); Rectangle r = s; ((Savings. Account)r). add. Interest(); 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(Bank. Account b) { System. out. println(“Acct. Number: ” + b. get. Account. Number()); System. out. println(“Balance $” + b. get. Balance()); } Cay Horstmann's Bank Account Example 24

Polymorphism Consider the following static method: public void static display(Bank. Account b) { System. out. println(“Acct. Number: ” + b. get. Account. Number()); System. out. println(“Balance $” + b. get. Balance()); } // Suppose we call it with the following code. What happens? public static void main(String args[]) { Bank. Account college. Fund = new Bank. Account(100); display(college. Fund); } Cay Horstmann's Bank Account Example 25

Polymorphism How about with this code? public void static display(Bank. Account b) { System. out. println(“Acct. Number: ” + b. get. Account. Number()); System. out. println(“Balance $” + b. get. Balance()); } public static void main(String args[]) { Savings. Account rainy. Day = new Savings. Account(100, . 10); display(rainy. Day); } Cay Horstmann's Bank Account Example 26

Inheritance Diagram (UML) Object Rectangle Bank. Account Savings. Account Cay Horstmann's Bank Account Example CDAccount 27

Polymorphism Is this OK? public void static display(Bank. Account b) { System. out. println(“Acct. Number: ” + b. get. Account. Number()); System. out. println(“Balance $” + b. get. Balance()); } 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 No 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 Checking. Account “is-a” Bank. Account. • Now, suppose that we have a routine that manipulates Bank. Account objects -static void foo(Bank. Account 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(Bank. Account x) { x. withdraw(1000); x. deposit(50. 0); : : } foo() can call those methods on x that are provided by the Bank. Account class Cay Horstmann's Bank Account Example 33

Inheritance // A Checking. Account “is-a” Bank. Account. class Checking. Account extends Bank. Account { } static void foo(Bank. Account x) { // do things to x } Should we be able to pass a Checking. Account object to Cay Horstmann's Bank Account this routine? Example 34

Inheritance // A Checking. Account “is-a” Bank. Account. class Checking. Account extends Bank. Account { } static void foo(Bank. Account x) { // do things to x } Should we be able to pass a Checking. Account 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 Bank. Account 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 Bank. Account class, the writer of foo() knows that the object has methods called “deposit” and “withdraw”. Since the object “is a” Bank. Account, 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 Bank. Account Again interface Account { public double get. Balance(); public void set. Balance(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 Bank. Account implements Account { private double balance; private double rate; public Bank. Account() { balance = 0; } public Bank. Account(double initial. Balance, double arate) { rate = arate / 100; ; balance = initial. Balance; 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 get. Balance() { return balance; } Cay Horstmann's Bank Account Example 40

public void set. Balance(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 Bank Account Test public static void mainString args Bank Account public class Bank. Account. Test { public static void main(String[] args) { Bank. Account](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-42.jpg)
public class Bank. Account. Test { public static void main(String[] args) { Bank. Account my. Account = new Bank. Account(1000, 10); int month; for (month = 1; month <= 2; month++) { my. Account. update(); Call foo() with an } my. Account. deposit(100); object that implements interface Account foo(my. Account); } Cay Horstmann's Bank Account Example 42

public static void foo(Account a) { double m = a. get. Balance(); 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 compare. To(Object other); } public class Student implements Comparable { // this class MUST define compare. To() } Cay Horstmann's Bank Account Example 46
![INTERFACES Suppose we have a function foo void fooComparable x Can we INTERFACES Suppose we have a function foo void foo(Comparable x[]) { } Can we](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-47.jpg)
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 fooComparable x Can we INTERFACES Suppose we have a function foo void foo(Comparable x[]) { } Can we](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-48.jpg)
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 Bank. Account { public void deduct. Fees() { …body goes here ? … } : : We silently get the } deduct. Fees() method public class Savings. Account extends Bank. Account{ } 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 Bank. Account { public abstract void deduct. Fees(); public double get. Balance() { return balance; } : } public class Savings. Account extends Bank. Account{ public void deduct. Fees() { // deduct fees according to // the account type } Cay Horstmann's Bank Account 51 } Example

Abstract Classes Abstract void foo(Bank. Account s) { } A real object make calls on s. deduct. Fees(); at run time. Many classes can extend the abstract class, get some code reuse, but are forced to define the abstract method deduct. Fees(). 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 Big. Integer) System. out. println("Found a Big Int"); } 54

Some type checking is automatic Object o = new Big. Integer("1234"); Big. Integer x = (Big. Integer)o; String st = (String)o; All casts are checked at run time. A Class. Cast. Exception is thrown when we try to convert the Big. Integer 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 is. Instance. Of // Given an object, check its type: public class Short. Test { public static void main(String args[]) { Object o = new Fruit(); if(o instanceof Fruit) System. out. println("it's a Fruit"); } } 57

instanceof and is. Instance. Of // Given a type, check an object public class Short. Test { public static void main(String args[]) { Object o = new Fruit(); Class c = o. get. Class(); if(c. is. Instance(o)) System. out. println("it's a Fruit"); } } 58

The Class Object interface Baby. Sitter { void respond. Fast(); } class Dad implements Baby. Sitter { public Dad() {} public void respond. Fast() {} } 59

public class RTTITest { public static void display. Info(Class c) { System. out. println(c. get. Name()); System. out. println(c. is. Interface()); System. out. println(c. is. Array()); } 60
![public static void mainString args throws Exception Class a Class for NameDad public static void main(String args[]) throws Exception { Class a = Class. for. Name("Dad");](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-61.jpg)
public static void main(String args[]) throws Exception { Class a = Class. for. Name("Dad"); // name could be entered at run // time. Dad is on the classpath. display. Info(a); Class b = Class. for. Name("Baby. Sitter"); display. Info(b); Class[] faces = a. get. Interfaces(); for(int i = 0; i < faces. length; i++) display. Info(faces[i]); Class sup = a. get. Superclass(); display. Info(sup); } } 61

C: Mc. CarthywwwJust. JavaExamples>java RTTITest Dad false Baby. Sitter true false java. lang. Object false 62

Creating an Object from a Name public class Fruit { private int grams; private int cals. Per. Gram; public Fruit() { this(0, 0); } public Fruit(int g, int c) { grams = g; cals. Per. Gram = c; } public String to. String() { return "Grams: " + grams + " Calories per gram: " + cals. Per. Gram; } } 63
![public class Test Fruit public static void mainString a throws Exception String public class Test. Fruit { public static void main(String a[]) throws Exception { String](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-64.jpg)
public class Test. Fruit { 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. for. Name(any). new. Instance(); System. out. println(m); } } C: Mc. CarthywwwJust. JavaExamples>java Test. Fruit 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 Test. Fruit { 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. for. Name(any). new. Instance(); // get the Class object Class c = o. get. Class(); Cay Horstmann's Bank Account Example 65

// if it's an array figure out its base type while(c. is. Array()) c = c. get. Component. Type(); // if c is not primitive then print its class hierarchy if(!c. is. Primitive()) { for(Class s = c; s != null; s = s. get. Superclass()) System. out. println(s. get. Name() + " extends"); } // get a to. String() method from the class passing an empty // array of arg types Method m = c. get. Method("to. String", 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: Mc. CarthywwwJust. JavaExamples>java Test. Fruit extends java. lang. Object extends Grams: 0 Calories per gram: 0 Cay Horstmann's Bank Account Example 67

Test. Exception. java class Bank. Balance. Exception extends Exception { Bank. Balance. Exception(String error. Message) { super(error. Message); } } Cay Horstmann's Bank Account Example 68

class Bank. Account { private double balance; public Bank. Account() { balance = 0; } public Bank. Account(double initial. Balance) throws Bank. Balance. Exception { if (initial. Balance < 0) throw new Bank. Balance. Exception("balance less than 0"); balance = initial. Balance; } 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 get. Balance() { return balance; } } Cay Horstmann's Bank Account Example 70
![public class Test Exception public static void mainString a Bank Account bill public class Test. Exception { public static void main(String a[]) { Bank. Account bill.](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-71.jpg)
public class Test. Exception { public static void main(String a[]) { Bank. Account bill. G = new Bank. Account(100. 0); Bank. Account mike. M = new Bank. Account(-230. 0); } } C: Mc. Carthywww95 -713examples>javac Test. Exception. java: 38: Exception Bank. Balance. Exception must be caught, or it must be declared in the throws clause of this method. Bank. Account bill. G = new Bank. Account(100. 0); ^ 1 error Cay Horstmann's Bank Account Example 71
![public class Test Exception Handle the exception public static void mainString a public class Test. Exception { Handle the exception public static void main(String a[]) {](https://slidetodoc.com/presentation_image_h/99f284603b213aee457c28e98fe7d31a/image-72.jpg)
public class Test. Exception { Handle the exception public static void main(String a[]) { try { Bank. Account bill. G = new Bank. Account(100. 0); Bank. Account mike. M = new Bank. Account(-230. 0); } catch(Bank. Balance. Exception 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: Mc. Carthywww95 -713examples>java Test. Exception Balance initialized too low Bank. Balance. Exception: 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 Run. Time. Exception Checked -Can be handled but rare e. g. Can occur anywhere -- These are all unchecked Class. Not. Found. Exception Unchecked 74 e. g. Null Pointer Exception, Clone. Not. Supported. Exceptio Array. Index. Out. Of. Bounds

Exceptions Checked Exceptions must be explicitly thrown or handled. The compiler will enforce this rule. Unchecked exceptions, for example Array. Index. Out. Of. Bounds, 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(Some. Throwable. Class e) { // The first catch clause that matches x runs // x caught here if x is a class or a subclass of e } catch(Some. Other. Throwable. Class e) { } finally { // this code runs unless the try performed System. exit() } Java in a Nutshell 76

Error is an Unchecked Exception class Bank. Balance. Exception extends Error { Bank. Balance. Exception(String error. Message) { super(error. Message); } } Cay Horstmann's Bank Account Example 77

class Bank. Account { private double balance; public Bank. Account() { balance = 0; } We don’t need a throws on our method for an unchecked exception. public Bank. Account(double initial. Balance) { if (initial. Balance < 0) throw new Bank. Balance. Exception("balance less than 0"); balance = initial. Balance; } 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 get. Balance() { return balance; } } public class Test. Exception { We don’t have to throw or catch an unchecked exception. public static void main(String a[]) { Bank. Account bill. G = new Bank. Account(100. 0); Bank. Account mike. M = new Bank. Account(-230. 0); } } Cay Horstmann's Bank Account Example 79

C: Mc. Carthywww95 -713examples>javac Test. Exception. java C: Mc. Carthywww95 -713examples>java Test. Exception in thread "main" Bank. Balance. Exception: balance less than 0 at Bank. Account. <init>(Test. Exception. java: 18) at Test. Exception. main(Test. Exception. java: 39) Cay Horstmann's Bank Account Example 80