java – 包含同一超类的不同对象的ArrayList – 如何访问子类的方法

前端之家收集整理的这篇文章主要介绍了java – 包含同一超类的不同对象的ArrayList – 如何访问子类的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨,我想知道我的问题是否有一个简单的解决方案,

我有一个ArrayList:

  1. ArrayList <Animal> animalList = new ArrayList<Animal>();
  2.  
  3. /* I add some objects from subclasses of Animal */
  4.  
  5. animalList.add(new Reptile());
  6. animalList.add(new Bird());
  7. animalList.add(new Amphibian());

它们都实现了一个方法move() – 当调用move()时,Bird会飞.
我知道我可以通过使用它来访问超类的常用方法属性

  1. public void Feed(Integer animalIndex) {
  2. Animal aAnimal = (Animal) this.animalList.get(animalIndex);
  3. aAnimal.eat();
  4. }

那没关系 – 但现在我想访问子类Bird所具有的move()方法.
我可以通过将动物像鸟一样投射来做到这一点:

  1. Bird aBird = (Bird) this.animalList.get(animalIndex);
  2. aBird.move();

在我的情况下,我不想这样做,因为这意味着我有3个不同的上述代码集,每个子​​类型为Animal.

这似乎有点多余,有更好的方法吗?

解决方法

从超类中确实没有很好的方法可以做到这一点,因为每个子类的行为都会有所不同.

要确保您实际调用适当的移动方法,请将Animal从超类更改为接口.然后,当您调用move方法时,您将能够确保为所需对象调用适当的移动方法.

如果你想保留公共字段,那么你可以定义一个抽象类AnimalBase,并要求所有动物构建它,但每个实现都需要实现Animal接口.

例:

  1. public abstract class AnimalBase {
  2. private String name;
  3. private int age;
  4. private boolean gender;
  5.  
  6. // getters and setters for the above are good to have here
  7. }
  8.  
  9. public interface Animal {
  10. public void move();
  11. public void eat();
  12. public void sleep();
  13. }
  14.  
  15. // The below won't compile because the contract for the interface changed.
  16. // You'll have to implement eat and sleep for each object.
  17.  
  18. public class Reptiles extends AnimalBase implements Animal {
  19. public void move() {
  20. System.out.println("Slither!");
  21. }
  22. }
  23.  
  24. public class Birds extends AnimalBase implements Animal {
  25. public void move() {
  26. System.out.println("Flap flap!");
  27. }
  28. }
  29.  
  30. public class Amphibians extends AnimalBase implements Animal {
  31. public void move() {
  32. System.out.println("Some sort of moving sound...");
  33. }
  34. }
  35.  
  36. // in some method,you'll be calling the below
  37.  
  38. List<Animal> animalList = new ArrayList<>();
  39.  
  40. animalList.add(new Reptiles());
  41. animalList.add(new Amphibians());
  42. animalList.add(new Birds());
  43.  
  44. // call your method without fear of it being generic
  45.  
  46. for(Animal a : animalList) {
  47. a.move();
  48. }

猜你在找的Java相关文章