Java Reference
In-Depth Information
In the first statement, e is cast to a Salary reference, but the resulting Salary
reference is not preserved. Notice that an extra set of parentheses is required
because of the order of operations. We want the cast to occur before the
method call. In the second statement, e is cast to a newly declared Salary refer-
ence f, and f is subsequently used to invoke computePay(). This technique is
more convenient if you need to invoke more than one method after casting.
The CastDemo program shown in Listing 8.3 demonstrates polymorphism
and casting references down the hierarchy tree. Study the program and try to
determine the output, which is shown in Figure 8.1.
public class CastDemo
{
public static void main(String [] args)
{
Salary s = new Salary(“George Washington”, “Valley Forge, DE”,
1, 5000.00);
System.out.println(s.getName() + “ “ + s.computePay());
Employee e = new Salary(“Rich Raposa”, “Rapid City, SD”,
47, 250000.00);
System.out.println(e.getName());
//e.computePay(); //Does not compile!
Salary f = (Salary) e;
System.out.println(f.getName() + “ “ + f.computePay());
s.mailCheck();
e.mailCheck();
f.mailCheck();
}
}
Listing 8.3
The CastDemo program casts an Employee reference to a Salary reference.
The Salary object in CastDemo for George Washington is referenced by a
Salary reference, so we can invoke methods like getName() and computePay()
with s. The Salary object for Rich Raposa is referenced by an Employee refer-
ence, so we can only invoke the Employee class methods like getName() using
e; however, when e is cast to a Salary reference:
Salary f = (Salary) e;
we can now use f to invoke any method in Salary or Employee.
Search WWH ::




Custom Search