Java provides a run-time operator instanceof to
compare a class and an instance of that class.
This operator " instanceof" compares an object to a
specified class type.
The instanceof operator is defined to know about an object's relationship with a class. It evaluates to true, if the object or array is an instance of the specified type; otherwise it returns false. The instanceof operator can be used with the arrays and objects. It can't be used with primitive data types and values. Its signature is written as:
|object instanceof type|
Lets have an example :
.Output of the Program:
x is an instance of X
obj is an instance of Z
In this example the class "Z" extends the class "X". So the expression " if (x instanceof X)" returns true because the object of class "X" has the reference to the object of class "Z". On the other hand, this example will generate an error, if the expression is written as "if (y instanceof X)" because the object "y" of class "Y" is not an object of class "X".
We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.
Posted on: December 18, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles