Your SlideShare is downloading. ×
  • Like
Polymorphism lecture 1
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Polymorphism lecture 1

  • 242 views
Published

 

Published in Technology , Business
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
242
On SlideShare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
20
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Copyright © 2000-2002 Tom Hunter
  • 2. Copyright © 2000-2002 Tom Hunterpublic 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 theoutput ofprogramTest?public class Apple extends Seed{public void grow(){System.out.println( “Apple grow” );}}
  • 3. Copyright © 2000-2002 Tom HunterIn Java the simplest category of variables are theprimitives.OOP Basicsint x;x = 0;The primitive variables are notnot objects.Only one slot in memory is used to hold thisvariable.1
  • 4. Copyright © 2000-2002 Tom Hunterx0• When we declare a primitive variable, it will occupy asingle slot in memory. That slot will contain the value.int x;x = 0;1 2 3 4 5 67 8 12111092
  • 5. Copyright © 2000-2002 Tom HunterNow, we want to build an object. I havedeclared “t” to be a reference to an object oftype Employee.At this point, the reference “t” does not point toany object.Soon, it will point to an object of typeEmployee, but now the object doesn’t exist.OOP BasicsEmployee t;3
  • 6. Copyright © 2000-2002 Tom HunterEmployee t = new Employee();When this statement executes, the newkeyword executes the default Constructorfor Employee, which actually creates an objectin memory and writes the location of that objectin t.Now t points to the new Employee object.OOP Vocabulary4
  • 7. Copyright © 2000-2002 Tom Hunter• It’s critical to understand the difference between areference and the object to which it refers.Employee t;t = new Employee();OOP Basics5
  • 8. Copyright © 2000-2002 Tom Huntert• 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
  • 9. Copyright © 2000-2002 Tom Hunter• Now, let’s explore this object called employee.OOP Basicspublic class Employee{}7
  • 10. Copyright © 2000-2002 Tom Hunter• I have added two instance variables: name and pay.OOP Basicspublic class Employee{private String name;private double pay;}8
  • 11. Copyright © 2000-2002 Tom Hunter• I have added a default constructor.OOP Basicspublic class Employee{private String name;private double pay;public Employee(){name = “”;pay = 0.0;}}9
  • 12. Copyright © 2000-2002 Tom Huntert• This is what we have done. The object has instancevariables, and methods we will use to operate on thoseinstance variables.• If I want to make a concrete instance of this class, I needanother class--a driver with a main method--to instantiatethis class.Employee t = new Employee();name=“” pay=0.010
  • 13. Copyright © 2000-2002 Tom Hunter• I have added gettersand setters for the name.This is all pretty trivialso far.• The purpose forexamining this class is tobetter understand itsreference.OOP Basicspublic 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
  • 14. Copyright © 2000-2002 Tom Huntert EmployeeEmployee()String getName()void setName( String)EmployeeEmployee()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
  • 15. Copyright © 2000-2002 Tom Hunterpublic 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 firststab at making this classdo some work. I havegiven it the‘calcPay()’ method.Unfortunately, thiscalcPay() method isonly useful for an hourlyemployee.OOP Basics13
  • 16. Copyright © 2000-2002 Tom Hunterpublic 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 itselfbecomes abstract.OOP Basics14
  • 17. Copyright © 2000-2002 Tom Hunterpublic 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 ofactions as this class isinstantiated?OOP BasicsSuperclassSubclass//Implicit call to Superclass constructor15
  • 18. Copyright © 2000-2002 Tom Hunterpublic 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
  • 19. Copyright © 2000-2002 Tom HunterSuperclasses and Subclasses• “is a”• Before the subclass HourlyEmployee object couldbe instantiated, we first had to instantiate thesuperclass Employee object.• A subclass is an instance of the superclass. It containseverything the superclass contains.• Because a subclass contains everything its superclasscontains, we can say: “A subclass is an instance of itssuperclass.”17
  • 20. Copyright © 2000-2002 Tom Hunter• Whenever you extended another class,(a Superclass) you have created an instance ofevery class above your classevery class above your class in the class hierarchy.• When the Constructor for HourlyEmployeefires, it silently also fires the Constructors forEmployee and every other class above it in thehierarchy.Superclasses and Subclassespublic class HourlyEmployee extends Employee{...}18
  • 21. Copyright © 2000-2002 Tom HunterSuperclasses and Subclasses• Every method, every data variable present in theSuperclass 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 ofthe classes above it.19
  • 22. Copyright © 2000-2002 Tom HunterThesuperReference20
  • 23. Copyright © 2000-2002 Tom Hunter• Already, we know that the Superclass-Subclassinteraction has a big effect on the Constructor.• The Superclass Constructors are either implicitlyor explicitly called first in the Constructor of aSubclass.The super Referencesuper( whatever the Superclass needs)21
  • 24. Copyright © 2000-2002 Tom HunterThe super Referencesuper( whatever the Superclass needs)• Using this super reference, you can call thecall theConstructorConstructor of your Subclass’ Direct Superclass.• If you use this super reference, then itmust be the very first statement in theSubclass’ Constructor.22
  • 25. Copyright © 2000-2002 Tom Hunterpublic 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
  • 26. Copyright © 2000-2002 Tom Hunterpublic 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
  • 27. Copyright © 2000-2002 Tom Hunter• There is a similar statement that is used to callyour Subclass’ constructor within your Subclass.• Don’t get the two confused.The super Referencesuper( whatever the Superclass needs)this( whatever the Subclass needs)25
  • 28. Copyright © 2000-2002 Tom HunterSubclass can beTreatedas an Objectof theSuperclass26
  • 29. Copyright © 2000-2002 Tom HunterSuperclasses and Subclasses• A Subclass contains more than its Superclasscontains.• Because of that, we say inside of a Subclass is acomplete copy of its Superclass.27
  • 30. Copyright © 2000-2002 Tom HunterSuperclasses and Subclasses• On previous slides, we said a Subclass is anobject of the Superclass type.• Now, we take that one step further.28
  • 31. Copyright © 2000-2002 Tom HunterSuperclasses and Subclasses• A Subclass contains everything ( and more)required to make a complete example of theSuperclass...• Thus, we say an object of a Subclass can betreatedtreated as an object of its Superclass.• In other words, in certain situations, we canignore the difference between the Superclassand Subclass objects.29
  • 32. Copyright © 2000-2002 Tom HunterSuperclasses and Subclasses“An object of a Subclass can be treatedas an object of its Superclass.”• What would stop this from being true?• Is there any part of the Superclass that ismissing from the Subclass?Nope—it’s all there.30
  • 33. Copyright © 2000-2002 Tom HunterSuperclasses and Subclasses“An object of a Subclass can be treatedas an object of its Superclass.”• Certainly if we are asking a Subclass tofill in for its parentfill in for its parent, we throw away theextra stuff that the Subclass added, but—because a Subclass “is an” example of itsSuperclass—we can “treat the Subclass asan example of the Superclass.”31
  • 34. Copyright © 2000-2002 Tom HunterSuperclasses and Subclasses• And, if we only want to call the methodsfrom the Superclassand access the data variables that comefrom the Superclass—what’s the difference?32
  • 35. Copyright © 2000-2002 Tom HunterSuperclasses and Subclasses• Doing this might be interesting.• As long as we treat the reference like it only refersto the Superclass, we can handle a Subclass objectfrom a Superclass “reference.”• As long as we only call the methods thatexist in the Superclass, this will work fine.33
  • 36. Copyright © 2000-2002 Tom Hunterpublic 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
  • 37. Copyright © 2000-2002 Tom Hunterpublic 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
  • 38. Copyright © 2000-2002 Tom Hunterpublic 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
  • 39. Copyright © 2000-2002 Tom Hunterpublic 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 thatexist in the Superclass, this will work fine.37
  • 40. Copyright © 2000-2002 Tom Hunterpublic 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
  • 41. Copyright © 2000-2002 Tom Hunterpublic class RetiredEmployeeextends Employee{double monthlyPension;public double calc_pay(){return monthlyPension;}}• Imagine if—after we built our system—wedecided to add a class, for Retired Employees.• If we had built our program on a Superclassreference, then we wouldn’t have to rebuildanything.• The runtime environment sees what kind of objectwe have instantiated, and calls the right methodoverride !39
  • 42. Copyright © 2000-2002 Tom Hunter40public 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 amethod that exists in your Superclass, not one thatexists only in the Subclass.(And so now you see the advantage of identifyinga bunch of empty methods in your Superclass.)
  • 43. Copyright © 2000-2002 Tom Hunter41Superclasses and Subclasses• And (drumroll…) the whole process is called...
  • 44. Copyright © 2000-2002 Tom Hunter42Superclasses and Subclasses• More on Polymorphism• We can create a Superclass reference that is anarray.• Then, when we instantiate the array, we can attachall different kinds of Subclass objects to theSuperclass array reference.
  • 45. Copyright © 2000-2002 Tom Hunter43Superclasses and Subclasses• As long as we’re only calling methods that existin the Superclass, we can work our way through thearray and it will call all the correct overriddenversions of each individual Subclass object.
  • 46. Copyright © 2000-2002 Tom Hunter44Superclasses and Subclasses• The Superclass reference only knows about themethods that exist in the Superclass.• The Superclass only tries to call the methods itknows about.• That’s perfectly fine, because all the methods inthe Superclass are available in its Subclass.
  • 47. Copyright © 2000-2002 Tom Hunter45Superclasses and Subclasses• Therefore the Superclass isn’t aware that theobject it references can do a whole lot more thanthe Superclass thinks it can.
  • 48. Copyright © 2000-2002 Tom Hunter46Superclasses and Subclasses• So, “We can create a Superclass reference arraythat actually points to a Subclass object.”• As long as we treat those Subclass objects as ifthey were Superclass objects, (meaning we onlycall the methods in the Superclass) we have noproblems.
  • 49. Copyright © 2000-2002 Tom Hunter47Superclasses and Subclasses• The Subclass knows how to do everything itsparent Superclass can do.• The kids can do everything the parent can.
  • 50. Copyright © 2000-2002 Tom Hunter48• However, if we try to do it the other way around—treating the Superclass as if it were one of itschildren—then we can have...Superclasses and Subclassesproblemsproblems• Why? The Subclass can do many things theSuperclass cannot.• The kids can do many things the parent cannot.
  • 51. Copyright © 2000-2002 Tom Hunter49Superclasses and Subclasses• If we called the Superclass with the Subclass’sreference, then you might expect the Subclassreference can do all the things the kids can—andyou’d be wrong!
  • 52. Copyright © 2000-2002 Tom Hunter50Superclasses and Subclasses• If you want to go the other way, attach aSuperclass object to a Subclass reference,you have to do an explicit cast, as a wayof informing the compiler that you reallywant to do this dumb thing.
  • 53. Copyright © 2000-2002 Tom Hunter51Superclasses 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)
  • 54. Copyright © 2000-2002 Tom Hunter52Superclasses and Subclasses• If you want to actually call some of themethods that don’t exist in the Superclass,then you have to first cast the object backto a reference of its own kind.
  • 55. Copyright © 2000-2002 Tom Hunter53A Case Study ofInheriting a Class:The Rosetta Stone of Inheritance
  • 56. Copyright © 2000-2002 Tom Hunter54• We have a class “Point” and its subclass“Circle”.A Case Study of Inheriting a Classpublic class Point{}public class Circle extends Point{}
  • 57. 55public 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 ){}}
  • 58. 56Point p;p = new Point();pCircle c;c = new Circle();c
  • 59. 57public 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 aSuperclassreference, pointingto a subclassobject.Is this legal?Is this useful?
  • 60. 58p = c;pcWhat if we try to call onlythe methods that both share?Will this “p” reference work correctly?This will work because any methodsone would expect to find in a Pointreference (p) already exist in the Circle object.
  • 61. 59c = p;pcNo ! A Circlereference wouldexpect manymethods that youwon’t find in aPoint object.Will this work for “c”?For this to even remotelywork, you would need to do a“downcast” ?
  • 62. Copyright © 2000-2002 Tom Hunter60A Case Study of Inheriting a Class• We’re attempting to do this error by casting aSubclass reference to a Superclass object.circleRef = (Circle) pointRef;• It’s useful to use the operator instanceofp instanceof Circle• This operator will tell us if p is a reference to anobject of type Circle.
  • 63. Copyright © 2000-2002 Tom Hunter61A Case Study of Inheriting a Class• Attempting to have a Superclass reference pointto a Subclass object would lead to an error knownas a ClassCastException.
  • 64. Copyright © 2000-2002 Tom Hunter62ImplicitSubclass-objecttoSuperclass-objectConversion
  • 65. Copyright © 2000-2002 Tom Hunter63• Joe was feeling entrepreneurial, and so hedecided to buy a piece of land in Arkansas.• Joe paid $50 for what the deed described as awooden shack in the swamp.• But, to his great surprise, when he got there,Joe discovered he hadn’t bought a shack in aswamp, but rather, the Taj Mahal on a beautifullake. Joe was ecstatic.• Joe got more than he was promised.
  • 66. Copyright © 2000-2002 Tom Hunter• Mary was feeling entrepreneurial, and so shedecided to buy a huge Mansion on an estate inArkansas.• Mary paid $5 Million for what the deeddescribed as a palatial estate on 40 acres.• But, to her great surprise, found she hadn’tbought a magnificent Mansion and estate, butrather, a Doublewide trailer next to a dump.Mary was horrified.• Mary got less than was promised.64
  • 67. Copyright © 2000-2002 Tom Hunter65• Joe’s situation is akin to Referring to aSubclass object with a Superclass reference.You get more than you expected.It’s a pleasant surprise.SuperclassRef = new SubclassObject
  • 68. Copyright © 2000-2002 Tom Hunter66• Mary’s situation is akin to Referring to aSuperclass object with a Subclass reference .You get less than you expected.It’s a tragic mistake.SubclassRef = new SuperclassObject
  • 69. Copyright © 2000-2002 Tom Hunter67Implicit Subclass-object to Superclass-object Conversion• There are four possible conversions that can occur:1.) Refer to aSuperclass object with aSuperclass reference.This is routine
  • 70. Copyright © 2000-2002 Tom Hunter68Implicit Subclass-object to Superclass-object Conversion2.) Refer to aSubclass object with aSubclass reference.This is also routine
  • 71. Copyright © 2000-2002 Tom Hunter69Implicit Subclass-object to Superclass-object Conversion3.) Refer to aSubclass object with aSuperclass referenceThis is safesafe because the Subclass object isis an object ofits Superclass.Such code can only refer to Superclass methods.
  • 72. Copyright © 2000-2002 Tom Hunter70Why might want to do that?Suppose many classes inherit from one Superclass.• You can make an array of Superclassreferences.• 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 thecorrect overridden method for each one!
  • 73. Copyright © 2000-2002 Tom Hunter71This process is known as...
  • 74. Copyright © 2000-2002 Tom Hunter72Implicit Subclass-object to Superclass-object Conversion4.) Refer to aSuperclass object with aSubclass reference .This is a syntax error! It doesn’t make sense. It is onlyremotely possible ifif the Subclass is explicitly cast into aSuperclass reference, which is a way of telling thecompiler you are doing this damn-fool thing with youreyes open.
  • 75. Copyright © 2000-2002 Tom Hunter73Implicit Subclass-object to Superclass-object ConversionSo, why is that a problem?Here’s the problem:A Subclass contains more and does more than itsSuperclass parent.If you use a Subclass reference to point to aSuperclass object, you are implying that the object has moredata variables available than it really does—and if someonemade that assumption—they would be sorely mistaken.
  • 76. Copyright © 2000-2002 Tom Hunter74The RightWay to UsePolymorphism
  • 77. Copyright © 2000-2002 Tom Hunter75class 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 ourSuperclass. As we see,it contains the instancevariable String ssn,a Constructor, theAccessor methodgetSSN() and theemptyempty methodcalcPay(), which wewill need to override inall the Subclassesbecause they will allneed to calculate paydifferently.
  • 78. Copyright © 2000-2002 Tom Hunterclass 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;}} 76Instance variablesspecific to the SubclassDefault ConstructorThe overridden methodinherited from theSuperclass.
  • 79. Copyright © 2000-2002 Tom Hunter77public 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 Employeecalled supEmp. However, we instantiate anHourlyEmployee object and assign the reference to theSuperclass Employee. This works because—after all—HourlyEmployee isis an Employee.
  • 80. Copyright © 2000-2002 Tom Hunter78public 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 );}}
  • 81. Copyright © 2000-2002 Tom Hunter79Superclass pay = 0.0Subclass pay = 113.0Superclass pay = 113.0Press any key to continue . . .
  • 82. Copyright © 2000-2002 Tom Hunter80The Wrong Way to UsePolymorphism—a SyntaxError—(Without AnExplicit Cast)
  • 83. Copyright © 2000-2002 Tom Hunter81public 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 atype HourlyEmployee. But instead of getting a Mansion(HourlyEmployee), the reference was assigned to aDoublewide Trailer (Employee). The object doesn’t have thesemethods and these message calls won’t work!
  • 84. Copyright © 2000-2002 Tom Hunter82C:CastSubTypeReftoSuperTypeObject.java:59:Incompatible type for declaration.Explicit cast needed to convert Employee to HourlyEmployee.HourlyEmployee subHrEmp = new Employee(); // Error!^1 errorTool completed with exit code 1At 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.
  • 85. Copyright © 2000-2002 Tom Hunterpublic class CastSubTypeReftoSuperTypeObject{double pay = 0;public CastSubTypeReftoSuperTypeObject(){ // Now we’ve Band-Aided the Error with An// Explicit castHourlyEmployee 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
  • 86. Copyright © 2000-2002 Tom Hunter84Exception in thread "main"java.lang.ClassCastException: Employee atCastSubTypeReftoSuperTypeObject.<init>(CastSubTypeReftoSuperTypeObject.java:60) atCastSubTypeReftoSuperTypeObject.main(CastSubTypeReftoSuperTypeObject.java:75)Press any key to continue . . .At this stage, the compiler is incensed—ittrusted us when we asked for that Explicit cast,and look what happened.