• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof operator

 
Jeet Jain
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 632
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeet Jain
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
no I said line 14. if(r instanceof Animal) System.out.print("5 "); How can this compile?
 
Pramod P Deore
Ranch Hand
Posts: 632
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4567
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ohhhh thank you so much got it finally
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic