Your SlideShare is downloading. ×
0
Copyright © 2000-2002 Tom Hunter
Copyright © 2000-2002 Tom Hunter
public class Seed
{
public void grow()
{
System.out.println( “Seed grow”);
}
}
public cla...
Copyright © 2000-2002 Tom Hunter
In Java the simplest category of variables are the
primitives.
OOP Basics
int x;
x = 0;
T...
Copyright © 2000-2002 Tom Hunter
x
0
• When we declare a primitive variable, it will occupy a
single slot in memory. That ...
Copyright © 2000-2002 Tom Hunter
Now, we want to build an object. I have
declared “t” to be a reference to an object of
ty...
Copyright © 2000-2002 Tom Hunter
Employee t = new Employee();
When this statement executes, the new
keyword executes the d...
Copyright © 2000-2002 Tom Hunter
• It’s critical to understand the difference between a
reference and the object to which ...
Copyright © 2000-2002 Tom Hunter
t
• When we declare a reference and instantiate the class,
the location of the object is ...
Copyright © 2000-2002 Tom Hunter
• Now, let’s explore this object called employee.
OOP Basics
public class Employee
{
}
7
Copyright © 2000-2002 Tom Hunter
• I have added two instance variables: name and pay.
OOP Basics
public class Employee
{
p...
Copyright © 2000-2002 Tom Hunter
• I have added a default constructor.
OOP Basics
public class Employee
{
private String n...
Copyright © 2000-2002 Tom Hunter
t
• This is what we have done. The object has instance
variables, and methods we will use...
Copyright © 2000-2002 Tom Hunter
• I have added getters
and setters for the name.
This is all pretty trivial
so far.
• The...
Copyright © 2000-2002 Tom Hunter
t Employee
Employee()
String getName()
void setName( String)
Employee
Employee()
String g...
Copyright © 2000-2002 Tom Hunter
public class Employee
{
private double pay;
private double rate;
private int hours;
publi...
Copyright © 2000-2002 Tom Hunter
public abstract class Employee
{
private double pay;
public Employee()
{
pay = 0.0;
}
pub...
Copyright © 2000-2002 Tom Hunter
public class HourlyEmployee extends Employee
{
private double rate;
private int hours;
pu...
Copyright © 2000-2002 Tom Hunter
public class Employee
{
public Employee()
{
System.out.println( “Employee constructor”);
...
Copyright © 2000-2002 Tom Hunter
Superclasses and Subclasses
• “is a”
• Before the subclass HourlyEmployee object could
be...
Copyright © 2000-2002 Tom Hunter
• Whenever you extended another class,
(a Superclass) you have created an instance of
eve...
Copyright © 2000-2002 Tom Hunter
Superclasses and Subclasses
• Every method, every data variable present in the
Superclass...
Copyright © 2000-2002 Tom Hunter
The
super
Reference
20
Copyright © 2000-2002 Tom Hunter
• Already, we know that the Superclass-Subclass
interaction has a big effect on the Const...
Copyright © 2000-2002 Tom Hunter
The super Reference
super( whatever the Superclass needs)
• Using this super reference, y...
Copyright © 2000-2002 Tom Hunter
public class HourlyEmployee extends Employee
{
double rate;
int hours;
public HourlyEmplo...
Copyright © 2000-2002 Tom Hunter
public class HourlyEmployee extends Employee
{
double rate;
int hours;
public HourlyEmplo...
Copyright © 2000-2002 Tom Hunter
• There is a similar statement that is used to call
your Subclass’ constructor within you...
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.
• Be...
Copyright © 2000-2002 Tom Hunter
Superclasses and Subclasses
• On previous slides, we said a Subclass is an
object of the ...
Copyright © 2000-2002 Tom Hunter
Superclasses and Subclasses
• A Subclass contains everything ( and more)
required to make...
Copyright © 2000-2002 Tom Hunter
Superclasses and Subclasses
“An object of a Subclass can be treated
as an object of its S...
Copyright © 2000-2002 Tom Hunter
Superclasses and Subclasses
“An object of a Subclass can be treated
as an object of its S...
Copyright © 2000-2002 Tom Hunter
Superclasses and Subclasses
• And, if we only want to call the methods
from the Superclas...
Copyright © 2000-2002 Tom Hunter
Superclasses and Subclasses
• Doing this might be interesting.
• As long as we treat the ...
Copyright © 2000-2002 Tom Hunter
public class Employee
{
String name;
String SSN;
public double calc_pay()
{
return 0.0;
}...
Copyright © 2000-2002 Tom Hunter
public class TestEmp
{
public static void main( String args[] )
{
double money = 0.0;
Hou...
Copyright © 2000-2002 Tom Hunter
public class TestEmp
{
public static void main( String args[] )
{
double money = 0.0;
Sal...
Copyright © 2000-2002 Tom Hunter
public class TestEmp
{
public static void main( String args[] )
{
double money = 0.0;
Emp...
Copyright © 2000-2002 Tom Hunter
public class TestEmp
{
public static void main( String args[] )
{
double money = 0.0;
Emp...
Copyright © 2000-2002 Tom Hunter
public class RetiredEmployee
extends Employee
{
double monthlyPension;
public double calc...
Copyright © 2000-2002 Tom Hunter40
public class TestEmp
{
public static void main( String args[] )
{
double money = 0.0;
E...
Copyright © 2000-2002 Tom Hunter41
Superclasses and Subclasses
• And (drumroll…) the whole process is called...
Copyright © 2000-2002 Tom Hunter42
Superclasses and Subclasses
• More on Polymorphism
• We can create a Superclass referen...
Copyright © 2000-2002 Tom Hunter43
Superclasses and Subclasses
• As long as we’re only calling methods that exist
in the S...
Copyright © 2000-2002 Tom Hunter44
Superclasses and Subclasses
• The Superclass reference only knows about the
methods tha...
Copyright © 2000-2002 Tom Hunter45
Superclasses and Subclasses
• Therefore the Superclass isn’t aware that the
object it r...
Copyright © 2000-2002 Tom Hunter46
Superclasses and Subclasses
• So, “We can create a Superclass reference array
that actu...
Copyright © 2000-2002 Tom Hunter47
Superclasses and Subclasses
• The Subclass knows how to do everything its
parent Superc...
Copyright © 2000-2002 Tom Hunter48
• However, if we try to do it the other way around
—treating the Superclass as if it we...
Copyright © 2000-2002 Tom Hunter49
Superclasses and Subclasses
• If we called the Superclass with the Subclass’s
reference...
Copyright © 2000-2002 Tom Hunter50
Superclasses and Subclasses
• If you want to go the other way, attach a
Superclass obje...
Copyright © 2000-2002 Tom Hunter51
Superclasses and Subclasses
• “A Superclass object is notnot a Subclass object.”
An Hou...
Copyright © 2000-2002 Tom Hunter52
Superclasses and Subclasses
• If you want to actually call some of the
methods that don...
Copyright © 2000-2002 Tom Hunter53
A Case Study of
Inheriting a Class:
The Rosetta Stone of Inheritance
Copyright © 2000-2002 Tom Hunter54
• We have a class “Point” and its subclass
“Circle”.
A Case Study of Inheriting a Class...
55
public class Point
{
}
public class Circle extends Point
{
}
public class Test
{
public Test()
{
Point p = new Point();...
56
Point p;
p = new Point();
p
Circle c;
c = new Circle();
c
57
public class Point
{
}
public class Circle extends Point
{
}
public class Test
{
public Test()
{
Point p = new Circle()...
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 w...
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 ...
Copyright © 2000-2002 Tom Hunter60
A Case Study of Inheriting a Class
• We’re attempting to do this error by casting a
Sub...
Copyright © 2000-2002 Tom Hunter61
A Case Study of Inheriting a Class
• Attempting to have a Superclass reference point
to...
Copyright © 2000-2002 Tom Hunter62
Implicit
Subclass-object
to
Superclass-object
Conversion
Copyright © 2000-2002 Tom Hunter63
• Joe was feeling entrepreneurial, and so he
decided to buy a piece of land in Arkansas...
Copyright © 2000-2002 Tom Hunter
• Mary was feeling entrepreneurial, and so she
decided to buy a huge Mansion on an estate...
Copyright © 2000-2002 Tom Hunter65
• Joe’s situation is akin to Referring to a
Subclass object with a Superclass reference...
Copyright © 2000-2002 Tom Hunter66
• Mary’s situation is akin to Referring to a
Superclass object with a Subclass referenc...
Copyright © 2000-2002 Tom Hunter67
Implicit Subclass-object to Superclass-object Conversion
• There are four possible conv...
Copyright © 2000-2002 Tom Hunter68
Implicit Subclass-object to Superclass-object Conversion
2.) Refer to a
Subclass object...
Copyright © 2000-2002 Tom Hunter69
Implicit Subclass-object to Superclass-object Conversion
3.) Refer to a
Subclass object...
Copyright © 2000-2002 Tom Hunter70
Why might want to do that?
Suppose many classes inherit from one Superclass.
• You can ...
Copyright © 2000-2002 Tom Hunter71
This process is known as...
Copyright © 2000-2002 Tom Hunter72
Implicit Subclass-object to Superclass-object Conversion
4.) Refer to a
Superclass obje...
Copyright © 2000-2002 Tom Hunter73
Implicit Subclass-object to Superclass-object Conversion
So, why is that a problem?
Her...
Copyright © 2000-2002 Tom Hunter74
The Right
Way to Use
Polymorphism
Copyright © 2000-2002 Tom Hunter75
class Employee
{
private String ssn;
public Employee()
{
ssn = "";
}
public Employee( S...
Copyright © 2000-2002 Tom Hunter
class HourlyEmployee extends Employee
{
double hourlyRate;
int hoursWorked;
public Hourly...
Copyright © 2000-2002 Tom Hunter77
public class DemoPolymorphism
{
double pay = 0;
public DemoPolymorphism()
{
Employee su...
Copyright © 2000-2002 Tom Hunter78
public class DemoPolymorphism
{
double pay = 0;
public DemoPolymorphism()
{
Employee su...
Copyright © 2000-2002 Tom Hunter79
Superclass pay = 0.0
Subclass pay = 113.0
Superclass pay = 113.0
Press any key to conti...
Copyright © 2000-2002 Tom Hunter80
The Wrong Way to Use
Polymorphism—a Syntax
Error—(Without An
Explicit Cast)
Copyright © 2000-2002 Tom Hunter81
public class CastSubTypeReftoSuperTypeObject
{
double pay = 0;
public CastSubTypeReftoS...
Copyright © 2000-2002 Tom Hunter82
C:CastSubTypeReftoSuperTypeObject.java:59:
Incompatible type for declaration.
Explicit ...
Copyright © 2000-2002 Tom Hunter
public class CastSubTypeReftoSuperTypeObject
{
double pay = 0;
public CastSubTypeReftoSup...
Copyright © 2000-2002 Tom Hunter84
Exception in thread "main"
java.lang.ClassCastException: Employee at
CastSubTypeReftoSu...
Upcoming SlideShare
Loading in...5
×

Understanding Polymorphism

283

Published on

Published in: Education, Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
283
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
38
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Understanding Polymorphism"

  1. 1. Copyright © 2000-2002 Tom Hunter
  2. 2. 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” ); } }
  3. 3. 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
  4. 4. 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
  5. 5. 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
  6. 6. 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
  7. 7. 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
  8. 8. 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
  9. 9. Copyright © 2000-2002 Tom Hunter • Now, let’s explore this object called employee. OOP Basics public class Employee { } 7
  10. 10. 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
  11. 11. 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
  12. 12. 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
  13. 13. 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
  14. 14. Copyright © 2000-2002 Tom Hunter t Employee Employee() String getName() void setName( String) 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
  15. 15. 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
  16. 16. 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
  17. 17. 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
  18. 18. 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
  19. 19. 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
  20. 20. 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 Subclasses public class HourlyEmployee extends Employee { ... } 18
  21. 21. 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
  22. 22. Copyright © 2000-2002 Tom Hunter The super Reference 20
  23. 23. 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
  24. 24. Copyright © 2000-2002 Tom Hunter The super Reference super( whatever the Superclass needs) • Using this super reference, you can call thecall 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
  25. 25. 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
  26. 26. 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
  27. 27. 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
  28. 28. Copyright © 2000-2002 Tom Hunter Subclass can be Treated as an Object of the Superclass 26
  29. 29. 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
  30. 30. 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
  31. 31. 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
  32. 32. 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
  33. 33. 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
  34. 34. 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
  35. 35. 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
  36. 36. Copyright © 2000-2002 Tom Hunter public class Employee { String name; String SSN; public double calc_pay() { return 0.0; } } public class HourlyEmployee extends Employee { double hourly_rate; int hours; public double calc_pay() { return hours * hourly_rate; } } public class SalariedEmployee extends Employee { double monthlySalary; public double calc_pay() { return monthlySalary; } } 34
  37. 37. 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
  38. 38. 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
  39. 39. 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
  40. 40. 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
  41. 41. 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
  42. 42. Copyright © 2000-2002 Tom Hunter40 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.)
  43. 43. Copyright © 2000-2002 Tom Hunter41 Superclasses and Subclasses • And (drumroll…) the whole process is called...
  44. 44. Copyright © 2000-2002 Tom Hunter42 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.
  45. 45. Copyright © 2000-2002 Tom Hunter43 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.
  46. 46. Copyright © 2000-2002 Tom Hunter44 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.
  47. 47. Copyright © 2000-2002 Tom Hunter45 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.
  48. 48. Copyright © 2000-2002 Tom Hunter46 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.
  49. 49. Copyright © 2000-2002 Tom Hunter47 Superclasses and Subclasses • The Subclass knows how to do everything its parent Superclass can do. • The kids can do everything the parent can.
  50. 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 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.
  51. 51. Copyright © 2000-2002 Tom Hunter49 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!
  52. 52. Copyright © 2000-2002 Tom Hunter50 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.
  53. 53. Copyright © 2000-2002 Tom Hunter51 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)
  54. 54. Copyright © 2000-2002 Tom Hunter52 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.
  55. 55. Copyright © 2000-2002 Tom Hunter53 A Case Study of Inheriting a Class: The Rosetta Stone of Inheritance
  56. 56. Copyright © 2000-2002 Tom Hunter54 • We have a class “Point” and its subclass “Circle”. A Case Study of Inheriting a Class public class Point { } public class Circle extends Point { }
  57. 57. 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 ) { } }
  58. 58. 56 Point p; p = new Point(); p Circle c; c = new Circle(); c
  59. 59. 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?
  60. 60. 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 methods one would expect to find in a Point reference (p) already exist in the Circle object.
  61. 61. 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” ?
  62. 62. Copyright © 2000-2002 Tom Hunter60 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.
  63. 63. Copyright © 2000-2002 Tom Hunter61 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.
  64. 64. Copyright © 2000-2002 Tom Hunter62 Implicit Subclass-object to Superclass-object Conversion
  65. 65. Copyright © 2000-2002 Tom Hunter63 • 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.
  66. 66. 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
  67. 67. Copyright © 2000-2002 Tom Hunter65 • 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
  68. 68. Copyright © 2000-2002 Tom Hunter66 • 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
  69. 69. Copyright © 2000-2002 Tom Hunter67 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
  70. 70. Copyright © 2000-2002 Tom Hunter68 Implicit Subclass-object to Superclass-object Conversion 2.) Refer to a Subclass object with a Subclass reference. This is also routine
  71. 71. Copyright © 2000-2002 Tom Hunter69 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.
  72. 72. Copyright © 2000-2002 Tom Hunter70 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!
  73. 73. Copyright © 2000-2002 Tom Hunter71 This process is known as...
  74. 74. Copyright © 2000-2002 Tom Hunter72 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 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.
  75. 75. Copyright © 2000-2002 Tom Hunter73 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.
  76. 76. Copyright © 2000-2002 Tom Hunter74 The Right Way to Use Polymorphism
  77. 77. Copyright © 2000-2002 Tom Hunter75 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.
  78. 78. 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.
  79. 79. Copyright © 2000-2002 Tom Hunter77 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.
  80. 80. Copyright © 2000-2002 Tom Hunter78 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 ); } }
  81. 81. Copyright © 2000-2002 Tom Hunter79 Superclass pay = 0.0 Subclass pay = 113.0 Superclass pay = 113.0 Press any key to continue . . .
  82. 82. Copyright © 2000-2002 Tom Hunter80 The Wrong Way to Use Polymorphism—a Syntax Error—(Without An Explicit Cast)
  83. 83. Copyright © 2000-2002 Tom Hunter81 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!
  84. 84. Copyright © 2000-2002 Tom Hunter82 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.
  85. 85. 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
  86. 86. Copyright © 2000-2002 Tom Hunter84 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.
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×