khernik
khernik

Reputation: 2091

Getting to the subclass from superclass objects list

I have one class, let's say - Animal. And a couple of classes that inherit from it, let's say: Bird, Cat, Dog.

Now I create an array list of type Animal, and add some instances of the subclasses to it.

private List<Animal> list = new ArrayList<Animal>();
list.add(new Bird());
list.add(new Bird());
list.add(new Cat());
list.add(new Dog());

Then I iterate through this list, call some methods, etc.

for(int i = 0; i < list.length; i++)
{
   list.get(i).makeSound();
}

Fine. But what if I want to add to the Bird subclass a method, that won't be implemented in the Animal superclass? Let's say, fly() method, so it would look like this:

for(int i = 0; i < list.length; i++)
{
   list.get(i).makeSound();
   if(list.get(i) instanceof Bird)
   {
      list.get(i).fly(); // error here
   }
}

It makes sense, but it throws an error - can't find the symbol. Implementing the method in the Animal class seems to solve the issue, but it hurts my eyes when I have to do that a couple of times. Is there a way to solve this issue?

Upvotes: 2

Views: 83

Answers (4)

spacemonkey
spacemonkey

Reputation: 133

its an array of animal references , only you know what the reference is actually pointing to , need to let the compiler know that via casting... at compile time the compiler will check the animal . class file and see if there is a makeNoise metbod , if there is it will not throw an error, at run time it will follow the animal reference amd see what it is actually pointing to and call that classes makeNoise metbod , as u stated there is no makeNoise method in your animal class so , yes casting is necessary. ...

Upvotes: 0

GoldenJam
GoldenJam

Reputation: 1510

You want to 'Cast' back to an instance of bird.

if(list.get(i) instanceof Bird)
{
    Bird bird = ((Bird) list.get(i));
}

I would also rewrite your loop to be a 'for each' loop as well:

for(Animal animal : list)
{
   animal.makeSound();
   if(animal instanceof Bird)
   {
      ((Bird) animal).fly(); 
   }
}

Upvotes: 0

GriffeyDog
GriffeyDog

Reputation: 8386

You need to cast to Bird:

((Bird)list.get(i)).fly(); 

Upvotes: 2

rgettman
rgettman

Reputation: 178313

If you have already determined that it's a Bird, then you can cast your Animal as a Bird, which allows you to call fly().

if(list.get(i) instanceof Bird)
{
   Bird bird = (Bird) list.get(i);
   bird.fly();
}

Upvotes: 1

Related Questions