• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

instanceOf doubt...

 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I have a doubt in using instanceOf.
In K&B page 113 (Reference variable casting) the following code is given.

if(animal instanceOf dog)
{
dog d = (dog) animal;
}
assuming that dog ISA animal.....

instanceOf operator is used to see if a class is a subclass of a superclass. but can we do the opposite?
Here dog ISA animal but vice versa is false. So how can "animal instanceOf dog" return true???
Can anyone explain??
Thanks
Sirisha
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Sirishaaaaa Ghatty:
...Here dog ISA animal but vice versa is false...


A reference of type Animal could refer to a Dog if the object was originally created as a Dog and its reference was upcast to type Animal. The instanceof test can be used to check this before attempting to downcast (which would cause a runtime exception if wrong).
 
Siri Naray
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks marc, i got the answer.
 
I claim this furniture in the name of The Ottoman Empire! You can keep this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic