ArrayList containing different objects of the same superclass - how to access method of a subclass

前端 未结 4 1537
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 09:51

Hi I\'m wondering if there is a simple solution to my problem,

I have an ArrayList:

ArrayList  animalList = new          


        
4条回答
  •  天涯浪人
    2021-01-18 10:34

    You dont need to do any casting. The overridden method should get called [simple polymorphism]

    Animal aAnimal==  this.animalList.get(animalIndex);
    aAnimal.move();
    

    Above code should call bird method if object is of bird, isn't it?

    And casting is not a solution , how will you decide which object to cast? You will have to use instanceOf.

提交回复
热议问题