aspose file tools*
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
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: 268
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: 3855

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: 39869
    
  28
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?
 
Consider Paul's rocket mass heater.
 
subject: instanceof Operator