Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof

 
Sam Samson
Ranch Hand
Posts: 63
IntelliJ IDE Java jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20955
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because Eatable is an interface, it could be in the same inheritance tree. Imagine you create a class like this:
 
Sam Samson
Ranch Hand
Posts: 63
IntelliJ IDE Java jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not quite "always" - see Paul's last paragraph.
 
Winston Gutkowski
Bartender
Pie
Posts: 10236
58
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic