• Post Reply Bookmark Topic Watch Topic
  • New Topic

Use of instance of function.  RSS feed

 
Vishal Kurkure
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In this code line no 12 gives true but why line no 11 doesnot give false?instead it gives a error saying " error: incompatible types: Integer cannot be converted to Long".What is the reason behind it?I know that i1 cannot be Long but compiler shold have given false rather that posting a error.
 
Junilu Lacar
Sheriff
Posts: 11486
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.20.2

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

Since an attempt to cast an Integer to a Long is a compile-time error, line 11 will also be a compile-time error.
 
Campbell Ritchie
Marshal
Posts: 56540
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I hope you are not planning to use instanceof frequently. Obviously here you are only trying to find out how it works, but frequent use of instanceof and frequent casts suggest you have got something wrong with your use of inheritance.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!