This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes instanceof Operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "instanceof Operator" Watch "instanceof Operator" New topic
Author

instanceof Operator

Siddharth Bhargava
Ranch Hand

Joined: Feb 23, 2007
Posts: 266
Hi All,

I didn't quite understand this statement :

"Even if the object being tested is not an actual instantiation of the class type on the right side of the operator, instanceof will still return true if the object being compared is assignment compatible with the type on the right."

given in the SCJP book by Kathy Sierra and Bert Bates.



In the above code I didn't quite understand the output of obj2. Please do explain and clear my concept.

Thanks
dhani kshirsagar
Greenhorn

Joined: Sep 19, 2009
Posts: 2
As i understand, the statement means that 'if the object [i.e. obj2] is not at instance of the parent class, but that object [obj2] is type of parent class then instanceof will return true".

-dk
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3826

Siddharth Bhargava wrote:In the above code I didn't quite understand the output of obj2. Please do explain and clear my concept.

obj2 is referring to an object of "Child" at runtime. But "Child" extends "Parent" so it inherits everything from the "Parent", hence instanceof returns true (this is what assignment compatible means in the below statement).
"Even if the object being tested is not an actual instantiation of the class type on the right side of the operator, instanceof will still return true if the object being compared is assignment compatible with the type on the right."



SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38474
    
  23
Never mind about "child" and "parent" (which are not the official Java terms anyway): look in the Java Language Specification and follow the link to ยง5.2 and see exactly what instanceof does. You will have to follow lots of links to find the whole story, and it is by no means easy to read.

You know that passing null to instanceof always results in false, don't you?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: instanceof Operator