使用instanceof运算符将参数强制转换为另一个类

时间:2018-03-17 23:58:36

标签: java

public void addAnimal (Animal ananimal)
{
    listOfAnimals.add(new Animal (ananimal));
}

Animal是一个抽象类,具有LandAnimal和WaterAnimal,它们都扩展(继承)Animal。 listOfAnimals是Animal类型的ArrayList。

如何使用instanceOf运算符将Animal参数强制转换为LandAnimal或WaterAnimal,以便方法addAnimal将Animal参数的副本添加到ArrayList?

2 个答案:

答案 0 :(得分:0)

similar to the answer above, I ended up using if statements.

if(anAnimal instanceof LandAnimal)
{
    LandAnimal animal1 = (LandAnimal) anAnimal;
    listOfAnimals.add(animal1);
}

The main reason I asked was because i kept getting an error hint that LandAnimal could not be converted from boolean.

答案 1 :(得分:-2)

public class Test {
    public static void main(String[] args) {
        Animal animal = new LandAnimal();

        for(Animal animal: animal.getList()){

            if (animal instanceof LandAnimal){
                LandAnimal temp = (LandAnimal) animal;
            }else if (animal instanceof WaterAnimal){
                WaterAnimal temp = (WaterAnimal) animal;
            }
        };


    }
}

abstract class Animal {
    private ArrayList<Animal> list = new ArrayList<>();

    public ArrayList<Animal> getList() {
        this.AddAnimal(new LandAnimal());
        this.AddAnimal(new WaterAnimal());
        this.AddAnimal(new LandAnimal());
        this.AddAnimal(new LandAnimal());
        return list;
    }

    public void AddAnimal(Animal animal) {
        this.getList().add(animal);
    }
}

class LandAnimal extends Animal {

}

class WaterAnimal extends Animal {

}

如果Animal是一个抽象类,则无法使用new关键字创建对象。