wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes instanceof operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "instanceof operator" Watch "instanceof operator" New topic
Author

instanceof operator

Jeet Jain
Ranch Hand

Joined: Sep 01, 2011
Posts: 53
Doesn't the instanceof operator not compile if is checking 2 completely unrelated types? Then why does line 14 compile? Robot and Animal are unrelated.

Jeet Jain
Ranch Hand

Joined: Sep 01, 2011
Posts: 53
If I replace Animal with any other class like String or some class I defined like Wheel it doesn't compile.
Pramod P Deore
Ranch Hand

Joined: Jul 15, 2008
Posts: 629

Jeet Jain wrote:Doesn't the instanceof operator not compile if is checking 2 completely unrelated types? Then why does line 14 compile? Robot and Animal are unrelated.



af is a actual object of Feline and BarnCat extends Feline .Therefore if(af instanceof BarnCat) doesn't give compile time error.


Life is easy because we write the source code.....
Jeet Jain
Ranch Hand

Joined: Sep 01, 2011
Posts: 53
no I said line 14. if(r instanceof Animal) System.out.print("5 "); How can this compile?
Pramod P Deore
Ranch Hand

Joined: Jul 15, 2008
Posts: 629

ohh my Bad Sorry

If the class is not a final class, the compiler can not determine what interfaces are implemented by it. Even if the class does not implement the interface, but one of its subclass might. If the actually object class does not implement the interface then you will get "false" at runtime. And String class is final so you get compile time error
Jeet Jain
Ranch Hand

Joined: Sep 01, 2011
Posts: 53
But it does not compile even if I put Feline or BarnCat instead of Animal at 14. But if I put any interface at 14. instead of Animal it compiles. I'm confused
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4338
    
    7

Comparing a class and an interface is always valid, because it's always possible to extend the class and implement the interface at the same time.

For example: Because of that, the test could work. The compiler will prevent comparisons that cannot work, which is when you have two classes from different inheritance branches. But because you can implement multiple interfaces, as soon as one of them is an interface the compiler has to allow it.
Jeet Jain
Ranch Hand

Joined: Sep 01, 2011
Posts: 53
ohhhh thank you so much got it finally
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instanceof operator
 
Similar Threads
Need explain instanceof operator issue
instanceof query
interface & abstract class code question
Downcasting
SCJP SE 5.0 official exam by sun