• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

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.
 
Oh sure, it's a tiny ad, but under the right circumstances, it gets bigger.
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic