wood burning stoves*
The moose likes Beginning Java and the fly likes instanceof Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instanceof" Watch "instanceof" New topic
Author

instanceof

Sam Samson
Ranch Hand

Joined: Oct 08, 2011
Posts: 61

Hi

I thought instanceof could only be used within the same inheritance tree. But why does line 17 compile? Chewable doesn't extend Eatable.

Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

With interfaces, there's a slightly subtle point you need to keep in mind: Even though Gum doesn't implement Eatable, the compiler can't be sure that the object the Gum reference points to doesn't.


Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18570
    
    8

If you have a class A and an interface B, then it's always possible that an instance of class A might implement interface B, regardless of how those two are defined. How could that be? Consider class C which is a subclass of A and which implements B: then a variable of type A might possibly refer to an instance of C, which does implement B. So that's why the compiler doesn't exclude the possibility in your example code.

I said "always" but that isn't quite right. If A is a final class which doesn't implement B, then none of its subclasses can implement B either, because it can't have any. The compiler will take that factor into account if it can; make your Gum class final and see what happens.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4392
    
    8

Because Eatable is an interface, it could be in the same inheritance tree. Imagine you create a class like this:
Sam Samson
Ranch Hand

Joined: Oct 08, 2011
Posts: 61

Smack my ass and call me Sally! (Sorry for that, but I couldn't resist, that translation was too funny )

So If the statement on the right of instanceof is an interface, it will always compile? No matter what?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4392
    
    8

Not quite "always" - see Paul's last paragraph.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7807
    
  21

Sam Samson wrote:So If the statement on the right of instanceof is an interface, it will always compile? No matter what?

Providing it's valid. In fact the name on the right can be any valid type: class, abstract class or interface.

The other nice (and oft-forgotten) thing about instanceof is that it won't return true if the object on the left is null. It's also pretty darn quick.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
 
Consider Paul's rocket mass heater.
 
subject: instanceof