wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes instanceof Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "instanceof" Watch "instanceof" New topic
Author

instanceof

Vijay Albuquerque
Ranch Hand

Joined: Feb 17, 2002
Posts: 42
I am unclear to distinguish between situations under which the instanceof operator generates a COMPILER ERROR and returns FALSE.
Could someone please throw some light on this issue.
Thanks in Advance.


Vijay Albuquerque
SCJP 1.4, SCWCD 1.3
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

* You'll get a compiler error if there's just NO way that the object can be an instanace of the class.
* You'll be returned false if at compile-time there's a chance that the object can be an instanceof the given class, but at run-time it turns out that its not...
* You'll be returned true if at compile-time there's a chance that the object can be an instanceof the given class, and at run-time it turns out it is.
Here's a bit of explanation with an example:

Ok... so in line 1 you're trying to see if a is an instance of Cat -- there is a possible relationship -- and the compiler knows that a compile-time (Cat extends Animal -- but it doesn't know at compile-time if this particular Animal object is an instance of the Cat class)... but at run-time, it turns out that it is not an instance of Cat, so it returns false
Same thing happens in line 2 (but with the class Dog)
In line 3 -- we're trying to compare a Cat object to the Dog class. Granted they both are subclasses of Animal -- but there's NO WAY that a Cat can be a Dog. so you get a compile-time error
In line 4 -- the compiler knows at compile time that there's a valid possible relationship between the Cat object and the Animal class -- and at runtime -- its still there it returns true
In line 5, just like in 1, the compiler knows the relationship is possible. And at run-time -- it turns out its there -- it returns true
Does that help??
[ January 04, 2003: Message edited by: Jessica Sant ]

- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
sam huang
Greenhorn

Joined: Dec 31, 2002
Posts: 28
Hi Jessica,
very good example!
Thank you very much

Sam


SCJP,SCWCD,SCBCD,MCSE
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8815
    
    5
Jessica -
Love those animal classes...


Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

Love those animal classes...
Well.. I was tempted to do

but for those poor poor underprivledged people who don't know what a MINI is... they might have been a tad confused.
[ January 04, 2003: Message edited by: Jessica Sant ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instanceof