File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof example not compiling

 
Phil Mahone
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The listed code gives a compile error as follows:
Ticker.java:9: inconvertible types
found : Ticker
required: Bub
boolean b = ( t instanceof Bub );
^
1 error

I was more expecting b to be assigned a 'false' at runtime since t is not a Bub. Why did a compiler error come up instead?
 
Joel McNary
Bartender
Posts: 1824
Eclipse IDE Java Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler errors at compile time because it knows that t can never be an instance of Bub. (t is a Ticker, Tickers are not Bubs, therefore t is not a Bub). This is along the same lines as a "while(false){...}" producing an "unreachable code" compiler error; the compiler thinks that you've made an error and is letting you know.
You can get around this by using the .isInstance() method of java.lang.Class

Now, you and I know that b will always be false, but the compiler cannot prove that, so it lets it slide.

Oh, another way around it is to declare t as an Object.

Now the compiler does not know that t is a Ticker; it could be anything. So the check to see if it is a Bub is a valid check.
In short, the declared type (not the run-time type) of the first parameter to instanceof must be a superclass* of the second parameter, or else the compiler knows that the expression will always be false and throw an error.
---
*OK, it can be a subclass too, which is silly because it will always evaluate to true. The compiler lets this one go, however.
[ May 27, 2003: Message edited by: Joel McNary ]
 
Richard Osama
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My suspicion is that it's because you're not having miso soup with every meal. Of course, one musn't discount the lack of frisbee golf or riding mountain bikes (particularly on McCulloch Peak). Anyway, just my opinion. ;-)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic