The instanceof Operator in Java

The instanceof operator determines if a given object is of the type of a specific class. To be more specific, the instanceof operator tests whether its first operand is an instance of its second operand. The test is made at runtime. The first operand is supposed to be the name of an object or an array element, and the second operand is supposed to be the name of a class, interface, or array type. The syntax is:

    <op1> instanceof <op2>

The result of this operation is a boolean: true or false. If an object specified by <op1> is an instance of a class specified by <op2>, the outcome of the operation is true, and otherwise is false. The outcome of the operation will also be true if <op2> specifies an interface that is implemented either by the class of the object specified by <op1> or by one of its superclasses.

For example, consider the following code fragment:

interface X{}
class A implements X {}
class B extends A {}
A a = new A();
B b = new B(); 

Note that class B does not implement the interface X directly, but class A does, and class B extends class A. Given this code, all of the following statements are true:

if( b instanceof X)
if (b instanceof B)
if(b instance of A)
if(a instance of A)
if(a instanceof X) 

Knowing the type of an object at runtime is useful for the following reasons:

• Some invalid casts (explicit type conversions) involving class hierarchies cannot be caught at compile time. Therefore, they must be checked at runtime (using the instanceof operator), to avoid a runtime error.
• You might have a situation where one process is generating various kinds of objects, and the other process is processing them. The other process may need to know the object type before it can properly process it. In this situation the instanceof operator would be helpful, too. 

Reference(s): SCJP Exam for J2SE 5 

No comments:

Post a Comment