• Post Reply Bookmark Topic Watch Topic
  • New Topic

Could you explain compile time error of this ?  RSS feed

 
Shalini Srivastav
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

b is not an instanceof Bird so why it can't return false for last test ? why compilation error ?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll get the following compiler error:

TestClass.java:12: error: inconvertible types
if(b instanceof Bird) System.out.println("f is a Bird");
^
required: Bird
found: Bat
1 error


That happens because in this case the compiler can already know beforehand that the result of the expression b instanceof Bird is always going to be false - just by checking the type of the variable b. If you change line 9, for example to the following, it will compile:

Because in that case, the compiler can't check just by looking at the type of b that the expression will always be false.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
instanceof works almost similar to casting notation. if there is no relation between two classes then you cant cast one to another.
similarly you cant do an instanceof test.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!