Java Reference
In-Depth Information
I want to relate the casting of references to the casting of primitive data
types. Using the Employee and Salary classes in Listings 8.1 and 8.2, suppose
we instantiate two Salary objects as follows:
Salary s = new Salary(“George Washington”,
“Valley Forge, DE”, 1, 5000.00);
Employee e = new Salary(“Rich Raposa”, “Rapid City, SD”, 47, 250000.00);
I want to emphasize that these two statements create two Salary objects; each
object consumes the same amount of memory and has the same methods and
fields allocated in memory. The only difference between these two objects is
the particular data stored in their respective fields.
Because s is a Salary reference, we can use s to invoke the accessible fields
and methods of both the Salary and Employee class. For example, the follow-
ing statements are valid:
s.setSalary(100000.00); //A Salary method
s.computePay(); //A Salary method
s.mailCheck(); //An Employee method
When going up the inheritance hierarchy, no casting is needed. For
example, a Salary reference can be used to invoke an Employee method
without casting because Employee is a parent of Salary. Going down the
hierarchy, however, requires an appropriate cast, as we will see next.
Because e is an Employee reference, we can use e to only invoke the accessible
methods of the Employee class. For example, we can use e to invoke mailCheck(),
but we cannot use e to invoke setSalary() or computePay():
e.setSalary(500000.00); //Does not compile!
e.computePay(); //Does not compile!
e.mailCheck(); //An Employee method, so this compiles
The Salary object referenced by e has a setSalary() and a mailCheck()
method; however, the compiler thinks e refers to an Employee, and attempting
to invoke setSalary() or mailCheck() generates a compiler error. We need to use
the cast operator on e, casting e to a Salary reference, before the Salary methods
can be invoked using e. The following statements demonstrate two techniques
for casting e to a Salary reference:
((Salary) e).computePay();
Salary f = (Salary) e;
f.computePay();
Search WWH ::




Custom Search