Java Reference
In-Depth Information
Figure 8.1
The output of the CastDemo program.
In the CastDemo program, there are two references to the Rich Raposa
object: e and f. We can use either reference to access the object. With e,
only the Employee methods can be invoked. With f, we can invoke
methods from either Salary or Employee. Invoking mailCheck() with both
references, as in:
e.mailCheck();
f.mailCheck();
simply invokes the method twice on the same object, since e and f point
to the same Salary object. Notice in Figure 8.1 that the output from
invoking mailCheck() with e or f is identical.
The instanceof Keyword
In the CastDemo program in Listing 8.3, an Employee reference was cast to a
Salary reference. The cast was successful because the object being cast was
actually a Salary object. If we had attempted to cast the object to something
that it wasn't, however, an exception would have occurred.
Let me demonstrate this with a specific example. The Salary class extends
Employee. Suppose that in Listing 8.4, the class named Hourly also extended
Employee.
public class Hourly extends Employee
{
private double hourlyRate, hoursWorked;
public Hourly(String name, String address, int number,
double hourlyRate)
{
Listing 8.4
The Hourly class extends the Employee class. (continued)
Search WWH ::




Custom Search