Java Reference
In-Depth Information
ClassCastException is the type of exception that occurs from poorly
written code. You should always use the instanceof operator to check the
data type of a reference before casting the reference, thereby averting any
chance of a ClassCastException.
The following InstanceOfDemo program in Listing 8.5 demonstrates the
instanceof operator. Study the program carefully and try to determine the out-
put, which is shown in Figure 8.2.
public class InstanceOfDemo
{
public static void main(String [] args)
{
Employee h = new Hourly(“Abe Lincoln”, “Springfield, IL”,
16, 8.00);
System.out.println(h.getName() + “ “ + h.getNumber());
if(h instanceof Salary)
{
System.out.println(“Casting to a Salary reference”);
Salary x = (Salary) h;
System.out.println(“Pay = “ + x.computePay());
x.mailCheck();
}
else if(h instanceof Hourly)
{
System.out.println(“Casting to an Hourly reference”);
Hourly x = (Hourly) h;
x.setHoursWorked(80);
System.out.println(“Pay = “ + x.computePay());
x.mailCheck();
}
System.out.println(“\nDeliberately cast to the wrong type”);
Salary s = (Salary) h;
s.computePay();
s.mailCheck();
System.out.println(“End of main”);
}
}
Listing 8.5 The InstanceOfDemo program uses instanceof to verify the data type of a
reference before casting.
Search WWH ::




Custom Search