• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

A question in JavaChamp about using "instanceof" that I didn't understand

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

I took the express exam on the JavaChamp site and encountered this question, the question is about the output of the code:



The solution is:


compilation error because of "gum instanceof Food"

The operands of instanceof must be in the same inheritance tree.

falsetruetrue



The solution is not clear for me.

My question is why it caused a compilation error and didn't print "false" instead?

I mean like the first print "food instanceof Eatable" it will print "false".

Why this worked and the third print didn't and they all implement Chewable? What is the difference?




 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Amd Dem, welcome to JavaRanch!

In the case of 'food instanceof Eatable' - it is possible that this line could return true. You can have a Food variable referencing something Eatable, as in the following example:
But 'gum instanceof Food' cannot possibly be true. Gum and Food are both classes which are unrelated to each other, so there is no way we can assign anything to a Gum reference that is also a Food object. So the compiler takes the view that, since it cannot possibly be true, to try and make the comparison must be an error.

This is closely related to casting. Try the following:
 
Amd Dem
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is now clear. Thanks!
 
reply
    Bookmark Topic Watch Topic
  • New Topic