aspose file tools
The moose likes Java in General and the fly likes instanceof Operator Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "instanceof Operator" Watch "instanceof Operator" New topic
Author

instanceof Operator

Siddharth Bhargava
Ranch Hand

Joined: Feb 23, 2007
Posts: 227
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: 3670

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: 32654
    
    4
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?
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: instanceof Operator
 
Similar Threads
Using instanceof operator
Downward casting
Problem with instanceof
conceptual problem !!!!!!
static - final - obj ref