Java Reference
In-Depth Information
Checked at compile time
Checked at runtime
a2
=
(K)
b2
Figure 16-2. Runtime and compile-time checks made for downcasting
the Object class is at the top of every class hierarchy in Java. this allows you to assign a reference of any
class type to a variable of the Object type. the following type of assignment is always allowed:
Tip
Object obj = new AnyJavaClass(); // Upcasting
Whether downcasting from an Object type to another class type will succeed depends on the downcasting rule as
discussed above.
The instanceof Operator
How can you be sure that a downcasting will always succeed at runtime? Java has an instanceof operator, which
helps you determine that whether a reference variable has a reference to an object of a class or a subclass of the class
at runtime. It takes two operands and evaluates to a boolean value true or false . Its syntax is
<<Class Reference Variable>>instanceof <<Class Name or Interface>>
If <<Class Reference Variable>>r efers to an object of class <<Class Name>>o r any of its descendants,
instanceof returns true . Otherwise, it returns false . Note that if <<Class Reference Variable>>i s null ,
instanceof always returns false .
You should use the instanceof operator before downcasting to check if the reference variable you are trying to
downcast is of the type you expected it to be. For example, if you want to check if a variable of Employee type refers to a
Manager object at runtime, you would write
Manager mgr = new Manager();
Employee emp = mgr;
if (emp instanceof Manager) {
// The following downcast will always succeed
mgr = (Manager)emp;
}
else {
// emp is not a Manager type
}
The instanceof operator goes through two types of checks: compile-time check and runtime check. The
compiler checks if it is ever possible for the left-hand operand to refer to an object of the right-hand operand. This
check may not be obvious to you at this point. The purpose of using the instanceof operator is to compare the
runtime type of a reference variable to a type. In short, it compares two types. Does it ever make sense to compare a
 
 
Search WWH ::




Custom Search