Nothing Special   »   [go: up one dir, main page]

Polymorphism Lecture 1.pps

Download as pps, pdf, or txt
Download as pps, pdf, or txt
You are on page 1of 86

Copyright © 2000-2002 Tom Hunter

public class Seed


{
public void grow()
{ What is the
System.out.println( “Seed grow”);
} output of
} program
public class Apple extends Seed Test?
{
public void grow()
{
System.out.println( “Apple grow” );
}
}
public class Test
{
public Test()
{
Seed x = new Apple();
x.grow();
}
public static void main( String[] args )
{
Test t = new Test();
}
}
Copyright © 2000-2002 Tom Hunter
OOP Basics
In Java the simplest category of variables are the
primitives.

int x;
x = 0;

The primitive variables are not objects.


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

1 Copyright © 2000-2002 Tom Hunter


int x;
x = 0;

1 2 3 4 5 6
x 0
7 8 9 10 11 12

• When we declare a primitive variable, it will occupy a


single slot in memory. That slot will contain the value.

2 Copyright © 2000-2002 Tom Hunter


OOP Basics
Employee t;

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.

3 Copyright © 2000-2002 Tom Hunter


OOP Vocabulary

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.

4 Copyright © 2000-2002 Tom Hunter


OOP Basics

• It’s critical to understand the difference between a reference


and the object to which it refers.

Employee t;

t = new Employee();

5 Copyright © 2000-2002 Tom Hunter


Employee t = new Employee();
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.

6 Copyright © 2000-2002 Tom Hunter


OOP Basics
public class Employee
{

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

7 Copyright © 2000-2002 Tom Hunter


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

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

8 Copyright © 2000-2002 Tom Hunter


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

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

• I have added a default constructor.

9 Copyright © 2000-2002 Tom Hunter


Employee t = new Employee();
t

name=“” pay=0.0

• 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.
10 Copyright © 2000-2002 Tom Hunter
OOP Basics
• I have added getters
public class Employee and setters for the name.
{
private String name;
This is all pretty trivial
private double pay; so far.
• The purpose for
public Employee()
{ examining this class is to
name = “”; better understand its
pay = 0.0; reference.
}
public String getName()
{
return name;
}
public void setName( String n )
{
name = n;
}
}
11 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 Copyright © 2000-2002 Tom Hunter
OOP Basics
public class Employee • Here I have made a
{ first stab at making this
private double pay;
private double rate;
class do some work. I
private int hours; have given it the
‘calcPay()’ method.
public Employee()
{
pay = 0.0; rate = 0.0; hours = 0;
}
public double getPay()
{ Unfortunately, this
return pay; calcPay() method is
}
public double calcPay() only useful for an hourly
{ employee.
pay = rate * hours;
}
}
13 Copyright © 2000-2002 Tom Hunter
OOP Basics
public abstract class Employee
{
private double pay; • Now, I’ve changed the
‘calcPay()’ method.
I’ve made it abstract.
public Employee()
{ Also, the class itself
pay = 0.0; becomes abstract.
}
public double getPay()
{
return pay;
}
public abstract double calcPay();

}
14 Copyright © 2000-2002 Tom Hunter
OOP Basics
public class HourlyEmployee extends Employee
{
private double rate;
private int hours; Superclass
Subclass
public HourlyEmployee( double r, int h )
{
//Implicit call to Superclass constructor
rate = r;
hours = h;
}

public double calcPay() • What is the sequence of


{ actions as this class is
return rate * hours;
} instantiated?

}
15 Copyright © 2000-2002 Tom Hunter
public class Employee
{ public class Object
public Employee() {
{ public Object()
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();
}
}

16 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 Copyright © 2000-2002 Tom Hunter
Superclasses and Subclasses
public class HourlyEmployee extends Employee
{
...
}

• Whenever you extended another class,


(a Superclass) you have created an instance of
every 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.
18 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 is an example of the
classes above it.

19 Copyright © 2000-2002 Tom Hunter


The
super
Reference

20 Copyright © 2000-2002 Tom Hunter


The super Reference
• 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.

super( whatever the Superclass needs)

21 Copyright © 2000-2002 Tom Hunter


The super Reference

super( whatever the Superclass needs)


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

• If you use this super reference, then it


must be the very first statement in the
Subclass’ Constructor.

22 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 Copyright © 2000-2002 Tom Hunter
public class HourlyEmployee extends Employee
{
double rate;
int hours;

public HourlyEmployee()
{
super( “”, “” ); // Explicit call to Superclass Constructor
rate = 0.0;
hours = 0;
}

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


{
super( n, s ); // Explicit call to Superclass Constructor
rate = r;
hours = h;
}

public double calc_pay()


{
return hours * rate;
}
}
24 Copyright © 2000-2002 Tom Hunter
The super Reference

super( whatever the Superclass needs)


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

this( whatever the Subclass needs)

• Don’t get the two confused.

25 Copyright © 2000-2002 Tom Hunter


Subclass can be
Treated
as an Object
of the
Superclass

26 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 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 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


treated as an object of its Superclass.

• In other words, in certain situations, we can


ignore the difference between the Superclass
and Subclass objects.
29 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 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 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 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 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 Copyright © 2000-2002 Tom Hunter


public class Employee
{ public class SalariedEmployee
String name; extends Employee
String SSN; {
double monthlySalary;
public double calc_pay()
{ public double calc_pay()
return 0.0; {
} return monthlySalary;
} }
}

public class HourlyEmployee


extends Employee
{
double hourly_rate;
int hours;

public double calc_pay()


{
return hours * hourly_rate;
}
}
34 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 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 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 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 Copyright © 2000-2002 Tom Hunter


public class RetiredEmployee
extends 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 Copyright © 2000-2002 Tom Hunter
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.)
40 Copyright © 2000-2002 Tom Hunter
Superclasses and Subclasses

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

41 Copyright © 2000-2002 Tom Hunter


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.

42 Copyright © 2000-2002 Tom Hunter


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.

43 Copyright © 2000-2002 Tom Hunter


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.

44 Copyright © 2000-2002 Tom Hunter


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.

45 Copyright © 2000-2002 Tom Hunter


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.

46 Copyright © 2000-2002 Tom Hunter


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

• The kids can do everything the parent can.

47 Copyright © 2000-2002 Tom Hunter


Superclasses and Subclasses

• 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...

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

• The kids can do many things the parent cannot.

48 Copyright © 2000-2002 Tom Hunter


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!

49 Copyright © 2000-2002 Tom Hunter


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.

50 Copyright © 2000-2002 Tom Hunter


Superclasses and Subclasses

• “A Superclass object is not 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)

51 Copyright © 2000-2002 Tom Hunter


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.

52 Copyright © 2000-2002 Tom Hunter


A Case Study of
Inheriting a Class:
The Rosetta Stone of Inheritance

53 Copyright © 2000-2002 Tom Hunter


A Case Study of Inheriting a Class

• We have a class “Point” and its subclass


“Circle”.

public class Point


{
}

public class Circle extends Point


{
}

54 Copyright © 2000-2002 Tom Hunter


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 )


{
}
}
55
Point p;
p = new Point();

Circle c;
c = new Circle();

56
public class Point
{
} Now, we have a
Superclass
public class Circle extends Point
{
reference, pointing
} to a subclass
object.
public class Test Is this legal?
{ Is this useful?
public Test()
{
Point p = new Circle();
Circle c = p;
}

public static void main( String[] args )


{
}
}
57
p = c; Will this “p” reference work correctly?

What if we try to call only


p
the methods that both share?

This will work because any methods


one would expect to find in a Point
reference (p) already exist in the Circle object.
58
c = p; Will this work for “c”?

No ! A Circle
reference would
c expect many
methods that you
For this to even remotely won’t find in a
work, you would need to do a Point object.
“downcast” ?
59
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.
60 Copyright © 2000-2002 Tom Hunter
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.

61 Copyright © 2000-2002 Tom Hunter


Implicit
Subclass-object
to
Superclass-object
Conversion
62 Copyright © 2000-2002 Tom Hunter
• 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.


63 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 Copyright © 2000-2002 Tom Hunter
• 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

65 Copyright © 2000-2002 Tom Hunter


• 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

66 Copyright © 2000-2002 Tom Hunter


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

67 Copyright © 2000-2002 Tom Hunter


Implicit Subclass-object to Superclass-object Conversion

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

This is also routine

68 Copyright © 2000-2002 Tom Hunter


Implicit Subclass-object to Superclass-object Conversion

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

This is safe because the Subclass object is an object of


its Superclass.

Such code can only refer to Superclass methods.


69 Copyright © 2000-2002 Tom Hunter
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 Superclass
objects.
• As long as you call methods that exist in
the Superclass (but were overridden
by each of the various Subclasses),
then the runtime system calls the
correct overridden method for each one!
70 Copyright © 2000-2002 Tom Hunter
This process is known as...

71 Copyright © 2000-2002 Tom Hunter


Implicit Subclass-object to Superclass-object Conversion

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

This is a syntax error! It doesn’t make sense. It is only


remotely possible if 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.
72 Copyright © 2000-2002 Tom Hunter
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.

73 Copyright © 2000-2002 Tom Hunter


The Right Way
to Use
Polymorphism

74 Copyright © 2000-2002 Tom Hunter


class Employee
{ Employee is our
private String ssn;
Superclass. As we see,
public Employee() it contains the instance
{
ssn = ""; variable String
} ssn, a Constructor, the
public Employee( String soc_num ) Accessor method
{
ssn = soc_num;
getSSN() and the
} empty method
public String getSSN() calcPay(), which
{ we will need to
return ssn;
} override in all the
Subclasses because
public double calcPay()
{ they will all need to
return 0;
}
calculate pay
} differently.
75 Copyright © 2000-2002 Tom Hunter
class HourlyEmployee extends Employee
{ Instance variables
double hourlyRate;
int hoursWorked; specific to the Subclass
public HourlyEmployee()
{ Default Constructor
hourlyRate = 0.0;
hoursWorked = 0;
}

public void setHourlyRate( double rate )


{
hourlyRate = rate;
}
The overridden method
inherited from the
public void setHoursWorked( int hours )
{ Superclass.
hoursWorked = hours;
}

public double calcPay()


{
return hourlyRate * hoursWorked;
}
} 76 Copyright © 2000-2002 Tom Hunter
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();
We declare a reference to "Superclass
System.out.println( an object ofpay = "Employee
type + pay );
called }public
supEmp. However,
static we String[]
void main( instantiate an)
args
HourlyEmployee
{ object and assign the reference to the
DemoPolymorphism demo = new DemoPolymorphism();
Superclass Employee.
System.exit( This
0 ); works because—after all—
}
HourlyEmployee
} is an Employee.
77 Copyright © 2000-2002 Tom Hunter
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 );
}
} 78 Copyright © 2000-2002 Tom Hunter
Superclass pay = 0.0
Subclass pay = 113.0
Superclass pay = 113.0
Press any key to continue . . .

79 Copyright © 2000-2002 Tom Hunter


The Wrong Way to Use
Polymorphism—a Syntax
Error—(Without An
Explicit Cast)

80 Copyright © 2000-2002 Tom Hunter


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 );
}
In the program, we know
public static that subHrEmp
void main( String[] argswas
) declared as a
type HourlyEmployee.
{ But instead of getting a Mansion
CastSubTypeReftoSuperTypeObject demo;
(HourlyEmployee), the reference was assigned to a
demo = new CastSubTypeReftoSuperTypeObject();
Doublewide Trailer (Employee).
System.exit( 0 ); The object doesn’t have these
} and these message calls won’t work!
methods
} 81 Copyright © 2000-2002 Tom Hunter
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.

82 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 Copyright © 2000-2002 Tom Hunter
Exception in thread "main"
java.lang.ClassCastException: Employee at
CastSubTypeReftoSuperTypeObject.<init>(CastS
ubTypeReftoSuperTypeObject.java:60) at
CastSubTypeReftoSuperTypeObject.main(CastSub
TypeReftoSuperTypeObject.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.

84 Copyright © 2000-2002 Tom Hunter

You might also like