Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confused with instanceof, please help

 
Siri Naray
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Animal
{
void makeNoise(){System.out.println("generic noise");}
}
class Dog extends Animal
{
void makeNoise() {System.out.println("bark");}
void playDead() {System.out.println( "roll over");}
}
class CastTest2
{
public static void main(String [] args)
{
Animal [] a = {new Animal(), new Dog(), new Animal()};
for(Animal animal : a)
{
animal.makeNoise();
if(animal instanceof Dog)
animal.playDead();
}
}
}

When i compile this code compiler gives an error at animal.playDead()

This is probably because at compile time "animal instanceof Dog" is true

But what about runtime?

When i modified the code i posted above

if(animal instanceof Dog)
System.out.println(" animal is an instanceof Dog" );

output
-------
generic noise
bark
animal is an instanceof Dog
generic noise

But when "animal instanceof Dog" is true output should be

generic noise
animal is an instanceof Dog
bark
animal is an instanceof Dog
generic noise
animal is an instanceof Dog

I am confused.. please help
Thank you
--------------------
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An Animal has no playDead() method. Your reference variable animal is of type Animal so you cannot do animal.playDead().

Now, if at runtime, you know animal is going to be a Dog (using instanceof), you can call playDead() on this object, but only if you promise the compiler that this Animal is really a Dog. So what you have to do is cast animal to a Dog like this: (Dog)animal.
Then you can call playdead() like this: ((Dog)animal).playDead().

So your code should be:

[ July 27, 2006: Message edited by: Barry Gaunt ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By using instanceof before the casting of the animal to a Dog you have avoided a possible ClassCastException. So instead of having a nasty RuntimeException appearing suddenly out of nowhere, you just don't call playDead() when it is inapproriate to do so - like on a ChargingHeffalump or a ManEatingTigger (or worse, a Snark which turns out to be a BooJum).
[ July 27, 2006: Message edited by: Barry Gaunt ]
 
Siri Naray
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You, its very clear now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic