aspose file tools*
The moose likes Beginning Java and the fly likes instanceof example not compiling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instanceof example not compiling" Watch "instanceof example not compiling" New topic
Author

instanceof example not compiling

Phil Mahone
Greenhorn

Joined: May 27, 2003
Posts: 3

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?


Phil Mahone<br />scjp1.4<br />I used to be clueless but I've turned that around 360 degrees.
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1824

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 ]

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Richard Osama
Greenhorn

Joined: Jun 06, 2003
Posts: 1
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. ;-)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instanceof example not compiling