File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Need explain instanceof operator issue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Need explain instanceof operator issue" Watch "Need explain instanceof operator issue" New topic

Need explain instanceof operator issue

matej spac

Joined: Apr 21, 2011
Posts: 28
I do not understand why instanceof operator is working as it is working. For example:

cause compilation error - this is clear, there is no IS-A relationship, Dog never ever could be a Cat.
But another example behaviour is weird for me:

works fine. It compiles and also run (and produce false of cource).
So tell me, in which universe Robot could be an Animal?
Why this don't cause compile error?

Paul Clapham

Joined: Oct 14, 2005
Posts: 18115

There could be a subclass of Robot which implements Animal. The compiler sees a variable of type Robot; this could be a reference to an instance of that subclass.

Try declaring the Robot class as "final" and see what changes.
matej spac

Joined: Apr 21, 2011
Posts: 28
wow, so briefly and so clearly :-)
thanks, now I understand
I agree. Here's the link:
subject: Need explain instanceof operator issue
Similar Threads
casting reference
instanceof operator
Reg. casting from Khalid Mughal
I'm not understanding why the instanceof operator results in compilation error
Casting reference types.