Java Reference
In-Depth Information
Figure 8.2
The output of the InstanceOfDemo program.
Notice in the output of the InstanceOfDemo program in Figure 8.2 that the
statement “End of main” is not displayed. A ClassCastException occurs at
the statement:
Salary s = (Salary) h;
This exception causes main() to stop executing, and your program
terminates. Therefore, the last three statements in main() do not execute.
The flow of control when an exception occurs is discussed in detail in
Chapter 11, “Exception Handling.”
Polymorphic Parameters
Now that we have discussed parent class references and the instanceof key-
word, I want to show you a benefit of polymorphism known as polymorphic
parameters. When a method has a parameter that is a reference, any object that
is compatible with that reference can be passed in, allowing a method to accept
parameters of different data types.
For example, suppose that a method has an Employee parameter:
public void payEmployee(Employee e)
An Employee object needs to be passed in to the payEmployee() method. If
Salary and Hourly extend Employee, a Salary or Hourly object could also be
passed in to payEmployee() because through polymorphism a Salary or
Hourly object is also an Employee object.
Having an Employee parameter makes payEmployee() a more generic
method in that its parameter is loosely defined. Presently, it can accept
Employee, Hourly, and Salary objects. If a new class came along that
extended Employee, say a class named Contractor, Contractor objects
could also be passed in to payEmployee().
Search WWH ::




Custom Search