Java Reference
In-Depth Information
Now, take a look at a new type of statement that at first glance might not
seem valid:
Employee p = new Salary(“Rich Raposa”, “Rapid City, SD”, 47, 250000.00);
The left side of the equation creates a reference p of type Employee. The
right side of the equation is a new Salary object. Can you assign an Employee
reference to point to a Salary object? Are they compatible data types?
The answer to both questions is yes. The is a relationship carries over to
polymorphism. The right side of the equation is a Salary object. A Salary object
is an Employee object. Can p refer to an Employee object? Certainly. In fact, p
can refer to an Employee object, and because a Salary object is an Employee
object, p can refer to a Salary object as well.
An Employee reference can refer to any Employee object. Because a
Salary object is an Employee object, an Employee reference can be used
to refer to a Salary object. This is an example of a parent class reference
referring to a child class object.
Classroom Q & A
Q: Why use an Employee reference to refer to a Salary object? Why
not just use a Salary reference?
A: There are situations where using a parent class reference can
make your code easier to write and easier to maintain. You can
think of an Employee reference as a more generic reference than a
Salary reference. Suppose that we have Hourly and Salary classes
that both extend Employee. I can then reference each employee's
object as either a Salary or Hourly, using a Salary or an Hourly ref-
erence. Or I can treat each employee's object as an Employee, and
use an Employee reference to refer to any employee, no matter
what data type the employee actually is.
Q: OK, but what do you gain from doing this?
A: By treating Hourly and Salary objects as type Employee, I can store
them in the same data structure (an example of a heterogeneous
collection). I can also write a method that has an Employee param-
eter, which allows both Salary and Hourly objects to be passed in
to that method (an example of polymorphic parameters).
Q: If you treat a Salary object as an Employee, don't you lose the
Salary part of the object?
Search WWH ::




Custom Search