-->

ArrayList的含有相同超类的不同的对象 - 如何访问一个子类的方法(ArrayList con

2019-08-22 22:10发布

您好我想知道如果有一个简单的解决我的问题,

我有一个ArrayList

ArrayList <Animal> animalList = new ArrayList<Animal>(); 

/* I add some objects from subclasses of Animal */

animalList.add(new Reptile());
animalList.add(new Bird());
animalList.add(new Amphibian());

它们都实现的方法move() -该Bird在飞move()被调用。 我知道我可以通过这个访问超类的常用方法和属性

public void feed(Integer animalIndex) {
    Animal aAnimal = (Animal) this.animalList.get(animalIndex);
    aAnimal.eat();
}

这很好-但现在我想访问move()方法的子类Bird都有。 我可以通过铸造做到这一点AnimalBird

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

在我的情况,我不想这样做,因为这将意味着我有3台不同的套以上代码之一的每个亚型Animal

这似乎有点多余,有没有更好的办法?

Answer 1:

是不是真的有一个很好的方式从父做到这一点,因为每个子类的行为会有所不同。

为了确保你实际上调用相应的move方法,改变Animal从一个超类的接口。 然后,当你调用move方法,你就可以保证你在呼唤你想要的对象适当的移动方法。

如果你正在寻找保存公共字段,那么你可以定义一个抽象类AnimalBase ,并要求所有的动物,以建立过这一点,但每个实施将需要实现Animal接口。

例:

public abstract class AnimalBase {
    private String name;
    private int age;
    private boolean gender;

    // getters and setters for the above are good to have here
}

public interface Animal {
    public void move();
    public void eat();
    public void sleep();
}

// The below won't compile because the contract for the interface changed.
// You'll have to implement eat and sleep for each object.

public class Reptiles extends AnimalBase implements Animal {
    public void move() {
        System.out.println("Slither!");
    }
}

public class Birds extends AnimalBase implements Animal {
    public void move() {
        System.out.println("Flap flap!");
    }
}

public class Amphibians extends AnimalBase implements Animal {
    public void move() {
        System.out.println("Some sort of moving sound...");
    }
}

// in some method, you'll be calling the below

List<Animal> animalList = new ArrayList<>();

animalList.add(new Reptiles());
animalList.add(new Amphibians());
animalList.add(new Birds());

// call your method without fear of it being generic

for(Animal a : animalList) {
    a.move();
}


Answer 2:

你不需要做任何的铸造。 重写的方法应该得到所谓的[简单的多态性]

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

上面的代码应该调用鸟方法,如果对象是鸟,是不是?

铸造是没办法了,你将如何决定哪个对象投? 你将不得不使用}这种。



Answer 3:

在你的情况下,以下可以工作,但时间复杂度为O(n):

public void moveBird(){
    for(Animal aminal:animalList){
        if(animal instanceof Bird){
            aninmal.move();
        }
    }
}


Answer 4:

Bird getMyBird(Integer aniInteger) {
        Bird b = new Bird();
        //Do somthig with bird object...

        return b;
        //get your modifeid bird object
    }

    Bird myBird = animalList.get(animalIndex);

    myBird.move();


文章来源: ArrayList containing different objects of the same superclass - how to access method of a subclass