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
If you worry you cannot work... If you work you need not worry
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).
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org