Java Reference
In-Depth Information
Employee h = new Hourly(“Abe Lincoln”, “Springfield, IL”, 16, 8.00);
((Hourly) h).setHoursWorked(40);
((Hourly) h).computePay();
h.mailCheck();
However, suppose I tried to cast the Hourly object to a Salary object:
Salary s = (Salary) h; //This compiles OK!
s.computePay(); //Which computePay() gets invoked?
Keep in mind that the compiler thinks h is an Employee, and casting an
Employee to a Salary is a compatible cast. This statement compiles, but there is
a problem looming. At run time, when h is cast to an Hourly object, a Class-
CastException will occur and the program will terminate. Java is very strict
about data types, and casting an Hourly object to type Salary is not valid
because the two types are not compatible.
By the way, invoking computePay() with s also compiles. Notice, too, in
the comment, that I asked “Which computePay() method gets invoked?”
More specifically, is it the computePay() in Hourly or the one in Salary?
The answer is neither because the cast one line above causes an
exception, and any ensuing statements will not execute.
What if you are not sure of the actual data type of h? Because h is of type
Employee, h can refer to an Employee object, a Salary object, or an Hourly
object. The instanceof keyword can be used to determine the data type of a ref-
erence. The syntax for using instanceof looks like:
reference instanceof ClassName
The instanceof operator returns true if the reference is of the given class
type, and false otherwise. For example, before casting h to a Salary object, we
should have made the following check:
if(h instanceof Salary)
{
Salary s = (Salary) h;
s.computePay();
//And so on
}
The cast above occurs only when h actually refers to a Salary object, so we
are guaranteed to avoid a ClassCastException when using the instanceof oper-
ator in this manner.
Search WWH ::




Custom Search