• 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

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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic