Java Reference
In-Depth Information
(HourlyEmployee) y
The real type of y is Executive , so to cast it to HourlyEmployee is a mistake,
and this mistake is sure to lead to a runtime error and abortion of execution.
4.2.3
Operator instanceof
At times, you may want to test what the real class of a variable is, so that you do
not make the mistake of casting an object to something that it is not. Use opera-
tor instanceof to do this. As an example, the following statement determines
whether the real type of x is HourlyEmployee and, if so, executes its then-part.
Activity
4-2.2
if (x instanceof HourlyEmployee) {
...
}
Operator instanceof can be useful. But if you find it necessary to use it fre-
quently, perhaps the structure of your classes is not adequate and some redesign
may be in order. If you find yourself writing code like that below, where you
have to test all possible subclasses, think about redesigning.
a9
Object
equals(Object)
toString()
wait()
getClass()
hashCode()
clone()
Employee
Employee(String, int )
getCompensation()
addToSalary( double )
toString() getName()
setName(String) getStart()
setStart( int )
Gries
name
1997
start
salary
50,000
HourlyEmployee
getHourlyPay()
getHoursWorked()
changeSalary( double d)
toString()
HourlyEmployee(String, int ,
double , int )
1600
hoursWorked
hourlyPay
15.00
PartTimeEmployee
components defined in class PartTimeEmployee
An instance of subclass PartTimeEmployee , showing the Object partition
Figure 4.7:
Search WWH ::




Custom Search