简体   繁体   中英

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?

您需要转换为Bird

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

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();
}

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(); 
   }
}

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. ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM