understanding polymorphism

86
Copyright © 2000-2002 Tom Hunter

Upload: gafna

Post on 20-Mar-2016

66 views

Category:

Documents


0 download

DESCRIPTION

Understanding Polymorphism. public class Seed { public void grow() { System.out.println( “Seed grow”); } }. What is the output of program Test?. public class Apple extends Seed { public void grow() { System.out.println( “Apple grow” ); } }. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Page 2: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class Seed{ public void grow() {

System.out.println( “Seed grow”); }}

public class Test{ public Test() { Seed x = new Apple(); x.grow(); } public static void main( String[] args ) { Test t = new Test(); }}

What is the output of program

Test?public class Apple extends Seed{ public void grow() { System.out.println( “Apple grow” ); }}

Page 3: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

In Java the simplest category of variables are the primitives.

OOP Basics

int x;

x = 0;

The primitive variables are notnot objects.

Only one slot in memory is used to hold this variable.

1

Page 4: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

x 0

• When we declare a primitive variable, it will occupy a single slot in memory. That slot will contain the value.

int x;x = 0;

1 2 3 4 5 6

7 8 1211109

2

Page 5: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Now, we want to build an object. I have declared “t” to be a reference to an object of type Employee.

At this point, the reference “t” does not point to any object.

Soon, it will point to an object of type Employee, but now the object doesn’t exist.

OOP Basics

Employee t;

3

Page 6: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Employee t = new Employee();

When this statement executes, the new keyword executes the default Constructor for Employee, which actually creates an object in memory and writes the location of that object in t.

Now t points to the new Employee object.

OOP Vocabulary

4

Page 7: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

• It’s critical to understand the difference between a reference and the object to which it refers.

Employee t;

t = new Employee();

OOP Basics

5

Page 8: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

t

• When we declare a reference and instantiate the class,the location of the object is written in the reference.The reference points to the object.

Employee t = new Employee();

6

Page 9: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

• Now, let’s explore this object called employee.

OOP Basics

public class Employee{

}

7

Page 10: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

• I have added two instance variables: name and pay.

OOP Basics

public class Employee{ private String name; private double pay;

}

8

Page 11: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

• I have added a default constructor.

OOP Basics

public class Employee{ private String name; private double pay;

public Employee() { name = “”; pay = 0.0; }}

9

Page 12: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

t

• This is what we have done. The object has instance variables, and methods we will use to operate on those instance variables.

• If I want to make a concrete instance of this class, I need another class--a driver with a main method--to instantiate this class.

Employee t = new Employee();

name=“” pay=0.0

10

Page 13: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

• I have added getters and setters for the name.This is all pretty trivial so far.• The purpose for examining this class is to better understand its reference.

OOP Basics

public class Employee{ private String name; private double pay;

public Employee() { name = “”; pay = 0.0; } public String getName() { return name; } public void setName( String n ) { name = n; }}

11

Page 14: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

t Employee

Employee()

String getName()

void setName( String)

Up close and personal with this reference. What do we know from this reference? We know:• It can point to some object. • It expects that object to be of type Employee.• It knows that the object has these methods.

12

Page 15: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class Employee{ private double pay; private double rate; private int hours; public Employee() { pay = 0.0; rate = 0.0; hours = 0; } public double getPay() { return pay; } public double calcPay() { pay = rate * hours; }}

• Here I have made a first stab at making this class do some work. I have given it the ‘calcPay()’ method.

Unfortunately, this calcPay() method is only useful for an hourly employee.

OOP Basics

13

Page 16: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public abstract class Employee{ private double pay; public Employee() { pay = 0.0; } public double getPay() { return pay; } public abstract double calcPay();

}

• Now, I’ve changed the ‘calcPay()’ method. I’ve made it abstract.Also, the class itself becomes abstract.

OOP Basics

14

Page 17: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class HourlyEmployee extends Employee{ private double rate; private int hours;

public HourlyEmployee( double r, int h ) {

rate = r; hours = h; } public double calcPay() {

return rate * hours; }

}

• What is the sequence of actions as this class is instantiated?

OOP Basics

SuperclassSubclass

//Implicit call to Superclass constructor

15

Page 18: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class Employee{ public Employee() { System.out.println( “Employee constructor”); } }

public class HourlyEmployee extends Employee{ public HourlyEmployee() { System.out.println( “HourlyEmployee constructor”); }}

public class TestEmployee{ public TestEmployee() {

HourlyEmployee he = new HourlyEmployee(); } public static void main( String[] args ) {

TestEmployee te = new TestEmployee(); }}

public class Object{ public Object() { }}

16

Page 19: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Superclasses and Subclasses• “is a”

• Before the subclass HourlyEmployee object could be instantiated, we first had to instantiate the superclass Employee object.

• A subclass is an instance of the superclass. It contains everything the superclass contains.

• Because a subclass contains everything its superclass contains, we can say: “A subclass is an instance of its superclass.”

17

Page 20: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

• Whenever you extended another class, (a Superclass) you have created an instance of every class above your classevery class above your class in the class hierarchy.

• When the Constructor for HourlyEmployee fires, it silently also fires the Constructors for Employee and every other class above it in the hierarchy.

Superclasses and Subclassespublic class HourlyEmployee extends Employee{

...}

18

Page 21: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Superclasses and Subclasses

• Every method, every data variable present in the Superclass is also present in the Subclass.

• Make sure you understand this:

If my class has everything above it—then I can say it isis an example of the classes above it.

19

Page 22: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

The super

Reference

20

Page 23: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

• Already, we know that the Superclass-Subclass interaction has a big effect on the Constructor.

• The Superclass Constructors are either implicitly or explicitly called first in the Constructor of a Subclass.

The super Reference

super( whatever the Superclass needs)

21

Page 24: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

The super Reference

super( whatever the Superclass needs)

• Using this super reference, you can call the call the ConstructorConstructor of your Subclass’ Direct Superclass.

• If you use this super reference, then it must be the very first statement in the Subclass’ Constructor.

22

Page 25: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class HourlyEmployee extends Employee{ double rate; int hours;

public HourlyEmployee() {

// implicit (hidden) call to Superclass Constructor.rate = 0.0;hours = 0;

}

public HourlyEmployee( double r, int h ) {

// implicit (hidden) call to Superclass Constructor.rate = r;hours = h;

}

public double calc_pay() { return hours * rate; } }

23

Page 26: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class HourlyEmployee extends Employee{ double rate; int hours;

public HourlyEmployee() {

super( “”, “” ); // Explicit call to Superclass Constructorrate = 0.0;hours = 0;

}

public HourlyEmployee( String n, String s, double r, int h ) {

super( n, s ); // Explicit call to Superclass Constructorrate = r;hours = h;

}

public double calc_pay() { return hours * rate; } }

24

Page 27: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

• There is a similar statement that is used to call your Subclass’ constructor within your Subclass.

• Don’t get the two confused.

The super Reference

super( whatever the Superclass needs)

this( whatever the Subclass needs)

25

Page 28: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Subclass can be Treated

as an Object of the

Superclass

26

Page 29: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Superclasses and Subclasses

• A Subclass contains more than its Superclass contains.

• Because of that, we say inside of a Subclass is a complete copy of its Superclass.

27

Page 30: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Superclasses and Subclasses

• On previous slides, we said a Subclass is an object of the Superclass type.

• Now, we take that one step further.

28

Page 31: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Superclasses and Subclasses

• A Subclass contains everything ( and more) required to make a complete example of the Superclass...

• Thus, we say an object of a Subclass can be treatedtreated as an object of its Superclass.

• In other words, in certain situations, we can ignore the difference between the Superclass and Subclass objects.

29

Page 32: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Superclasses and Subclasses

“An object of a Subclass can be treated as an object of its Superclass.”

• What would stop this from being true?

• Is there any part of the Superclass that is missing from the Subclass?

Nope—it’s all there.

30

Page 33: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Superclasses and Subclasses

“An object of a Subclass can be treated as an object of its Superclass.”

• Certainly if we are asking a Subclass to fill in for its parentfill in for its parent, we throw away the extra stuff that the Subclass added, but—because a Subclass “is an” example of its Superclass—we can “treat the Subclass as an example of the Superclass.”

31

Page 34: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Superclasses and Subclasses

• And, if we only want to call the methods

from the Superclass

and access the data variables that come

from the Superclass—what’s the difference?

32

Page 35: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

Superclasses and Subclasses

• Doing this might be interesting.

• As long as we treat the reference like it only refers to the Superclass, we can handle a Subclass object from a Superclass “reference.”

• As long as we only call the methods that exist in the Superclass, this will work fine.

33

Page 36: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class Employee{ String name; String SSN;

public double calc_pay() { return 0.0; }}

public class HourlyEmployeeextends Employee

{ double hourly_rate; int hours;

public double calc_pay() { return hours * hourly_rate; } }

public class SalariedEmployeeextends Employee

{ double monthlySalary;

public double calc_pay() { return monthlySalary; } }

34

Page 37: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class TestEmp{

public static void main( String args[] ){ double money = 0.0; HourlyEmployee hour; hour = new HourlyEmployee();

money = hour.calc_pay(); System.out.println( “Money=” + money );}

}

35

Page 38: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class TestEmp{

public static void main( String args[] ){ double money = 0.0; SalariedEmployee salr; salr = new SalariedEmployee();

money = salr.calc_pay(); System.out.println( “Money=” + money );}

}

36

Page 39: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class TestEmp{

public static void main( String args[] ){ double money = 0.0; Employee empl; empl = new SalariedEmployee();

money = empl.calc_pay(); System.out.println( “Money=” + money );}

}

• As long as we only call the methods that exist in the Superclass, this will work fine.

37

Page 40: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class TestEmp{

public static void main( String args[] ){ double money = 0.0; Employee empl; empl = new SalariedEmployee();

money = empl.calc_pay(); System.out.println( “Money=” + money );}

}

• So, why in the world might we want to do this?

38

Page 41: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class RetiredEmployeeextends Employee

{ double monthlyPension; public double calc_pay() { return monthlyPension; } } • Imagine if—after we built our system—we

decided to add a class, for Retired Employees.

• If we had built our program on a Superclass reference, then we wouldn’t have to rebuild anything.• The runtime environment sees what kind of object we have instantiated, and calls the right method override !

39

Page 42: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

40

public class TestEmp{

public static void main( String args[] ){ double money = 0.0; Employee empl; empl = new RetiredEmployee();

money = empl.calc_pay(); System.out.println( “Money=” + money );}

}

• Caution, this works only when you’re calling a method that exists in your Superclass, not one that exists only in the Subclass.(And so now you see the advantage of identifying a bunch of empty methods in your Superclass.)

Page 43: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

41

Superclasses and Subclasses

• And (drumroll…) the whole process is called...

Page 44: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

42

Superclasses and Subclasses

• More on Polymorphism

• We can create a Superclass reference that is an array.

• Then, when we instantiate the array, we can attach all different kinds of Subclass objects to the Superclass array reference.

Page 45: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

43

Superclasses and Subclasses

• As long as we’re only calling methods that exist in the Superclass, we can work our way through the array and it will call all the correct overridden versions of each individual Subclass object.

Page 46: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

44

Superclasses and Subclasses

• The Superclass reference only knows about the methods that exist in the Superclass.

• The Superclass only tries to call the methods it knows about.

• That’s perfectly fine, because all the methods in the Superclass are available in its Subclass.

Page 47: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

45

Superclasses and Subclasses

• Therefore the Superclass isn’t aware that the object it references can do a whole lot more than the Superclass thinks it can.

Page 48: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

46

Superclasses and Subclasses• So, “We can create a Superclass reference array that actually points to a Subclass object.”

• As long as we treat those Subclass objects as if they were Superclass objects, (meaning we only call the methods in the Superclass) we have no problems.

Page 49: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

47

Superclasses and Subclasses• The Subclass knows how to do everything its parent Superclass can do.

• The kids can do everything the parent can.

Page 50: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

48

• However, if we try to do it the other way around—treating the Superclass as if it were one of its children—then we can have...

Superclasses and Subclasses

problemsproblems• Why? The Subclass can do many things the Superclass cannot.

• The kids can do many things the parent cannot.

Page 51: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

49

Superclasses and Subclasses

• If we called the Superclass with the Subclass’s reference, then you might expect the Subclass reference can do all the things the kids can—and you’d be wrong!

Page 52: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

50

Superclasses and Subclasses

• If you want to go the other way, attach a Superclass object to a Subclass reference, you have to do an explicit cast, as a way of informing the compiler that you really want to do this dumb thing.

Page 53: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

51

Superclasses and Subclasses

• “A Superclass object is notnot a Subclass object.”

An HourlyEmployee is an Employee(Subclass is a Superclass object)

but…

An Employee is NOT an HourlyEmployee (Superclass is NOT a Subclass object)

Page 54: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

52

Superclasses and Subclasses

• If you want to actually call some of the methods that don’t exist in the Superclass, then you have to first cast the object back to a reference of its own kind.

Page 55: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

53

A Case Study of Inheriting a Class:

The Rosetta Stone of Inheritance

Page 56: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

54

• We have a class “Point” and its subclass “Circle”.

A Case Study of Inheriting a Class

public class Point{}

public class Circle extends Point{}

Page 57: Understanding Polymorphism

55

public class Point{}

public class Circle extends Point{}

public class Test{ public Test() {

Point p = new Point(); Circle c = new Circle(); }

public static void main( String[] args ) { }}

Page 58: Understanding Polymorphism

56

Point p;

p = new Point();

p

Circle c;

c = new Circle();

c

Page 59: Understanding Polymorphism

57

public class Point{}

public class Circle extends Point{}

public class Test{ public Test() {

Point p = new Circle();Circle c = p;

}

public static void main( String[] args ) { }}

Now, we have a Superclass

reference, pointing to a subclass

object.Is this legal?

Is this useful?

Page 60: Understanding Polymorphism

58

p = c;

p

c

What if we try to call only the methods that both share?

Will this “p” reference work correctly?

This will work because any methodsone would expect to find in a Point reference (p) already exist in the Circle object.

Page 61: Understanding Polymorphism

59

c = p;

p

c

No ! A Circle reference would expect many methods that you won’t find in a Point object.

Will this work for “c”?

For this to even remotely work, you would need to do a “downcast” ?

Page 62: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

60

A Case Study of Inheriting a Class

• We’re attempting to do this error by casting a Subclass reference to a Superclass object.

circleRef = (Circle) pointRef;

• It’s useful to use the operator instanceof

p instanceof Circle

• This operator will tell us if p is a reference to an object of type Circle.

Page 63: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

61

A Case Study of Inheriting a Class

• Attempting to have a Superclass reference point to a Subclass object would lead to an error known as a ClassCastException.

Page 64: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

62

Implicit Subclass-object

toSuperclass-object

Conversion

Page 65: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

63

• Joe was feeling entrepreneurial, and so he decided to buy a piece of land in Arkansas. • Joe paid $50 for what the deed described as a wooden shack in the swamp.

• But, to his great surprise, when he got there, Joe discovered he hadn’t bought a shack in a swamp, but rather, the Taj Mahal on a beautiful lake. Joe was ecstatic.

• Joe got more than he was promised.

Page 66: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

• Mary was feeling entrepreneurial, and so she decided to buy a huge Mansion on an estate in Arkansas. • Mary paid $5 Million for what the deed described as a palatial estate on 40 acres.

• But, to her great surprise, found she hadn’t bought a magnificent Mansion and estate, but rather, a Doublewide trailer next to a dump. Mary was horrified.

• Mary got less than was promised. 64

Page 67: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

65

• Joe’s situation is akin to Referring to a Subclass object with a Superclass reference.

You get more than you expected. It’s a pleasant surprise.

SuperclassRef = new SubclassObject

Page 68: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

66

• Mary’s situation is akin to Referring to a Superclass object with a Subclass reference .

You get less than you expected. It’s a tragic mistake.

SubclassRef = new SuperclassObject

Page 69: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

67

Implicit Subclass-object to Superclass-object Conversion

• There are four possible conversions that can occur:

1.) Refer to a Superclass object with a Superclass reference.

This is routine

Page 70: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

68

Implicit Subclass-object to Superclass-object Conversion

2.) Refer to a Subclass object with a Subclass reference.

This is also routine

Page 71: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

69

Implicit Subclass-object to Superclass-object Conversion

3.) Refer to a Subclass object with a Superclass reference

This is safesafe because the Subclass object isis an object of its Superclass.

Such code can only refer to Superclass methods.

Page 72: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

70

Why might want to do that?

Suppose many classes inherit from one Superclass. • You can make an array of Superclass

references. • Then, you can treat them all the same,

as if they really were all Superclassobjects.

• As long as you call methods that exist inthe Superclass (but were overriddenby each of the various Subclasses), then the runtime system calls the correct overridden method for each one!

Page 73: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

71

This process is known as...

Page 74: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

72

Implicit Subclass-object to Superclass-object Conversion

4.) Refer to a Superclass object with aSubclass reference .

This is a syntax error! It doesn’t make sense. It is only remotely possible ifif the Subclass is explicitly cast into a Superclass reference, which is a way of telling the compiler you are doing this damn-fool thing with your eyes open.

Page 75: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

73

Implicit Subclass-object to Superclass-object Conversion

So, why is that a problem?

Here’s the problem:A Subclass contains more and does more than its

Superclass parent.

If you use a Subclass reference to point to a Superclass object, you are implying that the object has more data variables available than it really does—and if someone made that assumption—they would be sorely mistaken.

Page 76: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

74

The Right Way to Use

Polymorphism

Page 77: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

75

class Employee{

private String ssn;

public Employee(){

ssn = "";}

public Employee( String soc_num ){

ssn = soc_num;}

public String getSSN(){

return ssn;}

public double calcPay(){

return 0;}

}

Employee is our Superclass. As we see, it contains the instance

variable String ssn, a Constructor, the Accessor method getSSN() and the

emptyempty method calcPay(), which we will need to override in

all the Subclasses because they will all need to calculate pay

differently.

Page 78: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

class HourlyEmployee extends Employee{

double hourlyRate;int hoursWorked;

public HourlyEmployee(){

hourlyRate = 0.0;hoursWorked = 0;

}

public void setHourlyRate( double rate ){

hourlyRate = rate;}

public void setHoursWorked( int hours ){

hoursWorked = hours;}

public double calcPay(){

return hourlyRate * hoursWorked;}

} 76

Instance variables specific to the Subclass

Default Constructor

The overridden method inherited from the Superclass.

Page 79: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

77

public class DemoPolymorphism{

double pay = 0;public DemoPolymorphism(){

Employee supEmp = new HourlyEmployee();HourlyEmployee subHrEmp = new HourlyEmployee();

pay = supEmp.calcPay();System.out.println( "Superclass pay = " + pay );

subHrEmp.setHourlyRate( 5.65 );subHrEmp.setHoursWorked( 20 );pay = subHrEmp.calc_Pay();System.out.println( "Subclass pay = " + pay );

supEmp = subHrEmp;pay = supEmp.calcPay();System.out.println( "Superclass pay = " + pay );

}public static void main( String[] args ){

DemoPolymorphism demo = new DemoPolymorphism();System.exit( 0 );

}}

We declare a reference to an object of type Employee called supEmp. However, we instantiate an HourlyEmployee object and assign the reference to the Superclass Employee. This works because—after all—HourlyEmployee isis an Employee.

Page 80: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

78

public class DemoPolymorphism{

double pay = 0;public DemoPolymorphism(){

Employee supEmp = new HourlyEmployee();HourlyEmployee subHrEmp = new HourlyEmployee();

pay = supEmp.calcPay();System.out.println( "Superclass pay = " + pay );

subHrEmp.setHourlyRate( 5.65 );subHrEmp.setHoursWorked( 20 );pay = subHrEmp.calc_Pay();System.out.println( "Subclass pay = " + pay );

supEmp = subHrEmp;pay = supEmp.calcPay();System.out.println( "Superclass pay = " + pay );

}public static void main( String[] args ){

DemoPolymorphism demo = new DemoPolymorphism();System.exit( 0 );

}}

Page 81: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

79

Superclass pay = 0.0Subclass pay = 113.0Superclass pay = 113.0Press any key to continue . . .

Page 82: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

80

The Wrong Way to Use Polymorphism—a Syntax

Error—(Without An Explicit Cast)

Page 83: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

81

public class CastSubTypeReftoSuperTypeObject{

double pay = 0;public CastSubTypeReftoSuperTypeObject(){ // Syntax Error ! ! ! HourlyEmployee subHrEmp = new Employee(); // Error!

// The error is not yet revealed. pay = subHrEmp.calcPay(); System.out.println( "Subclass pay = " + pay );

// Error because the object doesn’t have these // methods available.

subHrEmp.setHourlyRate( 5.67 ); subHrEmp.setHoursWorked( 20 ); pay = subHrEmp.calcPay(); System.out.println( "Subclass pay = " + pay );}public static void main( String[] args ){ CastSubTypeReftoSuperTypeObject demo; demo = new CastSubTypeReftoSuperTypeObject();

System.exit( 0 );}

}

In the program, we know that subHrEmp was declared as a type HourlyEmployee. But instead of getting a Mansion (HourlyEmployee), the reference was assigned to a Doublewide Trailer (Employee). The object doesn’t have these methods and these message calls won’t work!

Page 84: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

82

C:\CastSubTypeReftoSuperTypeObject.java:59: Incompatible type for declaration. Explicit cast needed to convert Employee to HourlyEmployee.

HourlyEmployee subHrEmp = new Employee(); // Error! ^

1 error

Tool completed with exit code 1

At this point, the compiler is extremely unhappy.So, let’s give it what it is specifically asking for—an explicit cast—and see what happens then.

Page 85: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

public class CastSubTypeReftoSuperTypeObject{

double pay = 0;public CastSubTypeReftoSuperTypeObject(){ // Now we’ve Band-Aided the Error with An

// Explicit cast HourlyEmployee subHrEmp; subHrEmp = (HourlyEmployee) new Employee();

// The error is not yet revealed. pay = subHrEmp.calcPay(); System.out.println( "Subclass pay = " + pay );

// Error because the object doesn’t have these // methods available.

subHrEmp.setHourlyRate( 5.67 ); subHrEmp.setHoursWorked( 20 ); pay = subHrEmp.calcPay(); System.out.println( "Subclass pay = " + pay );}public static void main( String[] args ){ CastSubTypeReftoSuperTypeObject demo; demo = new CastSubTypeReftoSuperTypeObject(); System.exit( 0 );}

}83

Page 86: Understanding Polymorphism

Copyright © 2000-2002 Tom Hunter

84

Exception in thread "main" java.lang.ClassCastException: Employee at CastSubTypeReftoSuperTypeObject.<init>(CastSubTypeReftoSuperTypeObject.java:60) at CastSubTypeReftoSuperTypeObject.main(CastSubTypeReftoSuperTypeObject.java:75)

Press any key to continue . . .

At this stage, the compiler is incensed—it trusted us when we asked for that Explicit cast, and look what happened.