Java Reference
In-Depth Information
Java syntax: Class cast
( class-name ) class-expression
Example : (Executive) d
Meaning : evaluation yields a view of the value
of class-expression with apparent type class-
name . It does not change the real type.
Java syntax: Operator instanceof
expression instanceof class-name
Example : d instanceof Executive
Meaning : evaluation yields true if the real
class of expression is class-name (or a sub-
class of class-name ) and false otherwise.
One may ask why one would want to put an Executive object in an
Employee variable. Here is a reason. Below is a static function that yields the
maximum compensation of two employees:
/** = the maximum compensation of e1 and e2 */
public static double max(Employee e1, Employee e2) {
return Math.max(e1.getCompensation(),
e2.getCompensation());
}
Now consider the following assignments:
Executive e= ...;
HourlyEmployee h= ...;
double m= max(e, h);
In the call max(e, h) , argument e is of class Executive and the corresponding
parameter e1 is of class Employee . Therefore, during evaluation of the call, the
apparent type of e1 is Employee but its real type is Executive . Hence, when the
call e1.getCompensation() in the method body is evaluated, it will call the
overriding function getCompensation that is defined in class Executive . This
makes sense: e1 is an Executive , so its compensation should be calculated
according to executive's rules. Similarly, the call e2.getCompensation() in the
method body will call the overriding method that is in the HourlyEmployee par-
tition of folder h.
Below, we summarize the important points about the apparent class and real
class of an expression:
The apparent class (or apparent type) of an expression is a syntactic
property; it is used to determine what component references are syntacti-
cally legal. For a class variable, its apparent class is the class with which
it was declared.
The real class (or real type) of an expression is a semantic property. It is
the class of the value of the expression, and it can change while the pro-
gram is executing. The real class of an expression determines which com-
ponents are actually referenced —for a call to a public method, the over-
riding method in the real class is called.
Search WWH ::




Custom Search