Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof Operator

 
Siddharth Bhargava
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3914
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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."


 
Campbell Ritchie
Sheriff
Pie
Posts: 49770
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic