Java: Getting the subclass from a superclass list

老子叫甜甜 提交于 2019-12-08 19:37:53

问题


i'm new with java and have 2 questions about the following code:

class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }
class Rat extends Animal { }

class Main {
  List<Animal> animals = new ArrayList<Animal>();

  public void main(String[] args) {
    animals.add(new Dog());
    animals.add(new Rat());
    animals.add(new Dog());
    animals.add(new Cat());
    animals.add(new Rat());
    animals.add(new Cat());

    List<Animal> cats = getCertainAnimals( /*some parameter specifying that i want only the cat instances*/ );
  }
}

1) Is there any way to get either the Dog or Cat instances from the Aminal list? 2) If yes, how should i correctly build the getCertainAnimals method?


回答1:


Animal a = animals.get(i);   

if  (a instanceof Cat)
{
    Cat c = (Cat) a;
} 
else if (a instanceof Dog)
{
    Dog d = (Dog) a;
} 

NB: It will compile if you do not use instanceof, but it will also allow you to cast a to Cat or Dog, even if the a is a Rat. Despite compiling, you will get a ClassCastException on runtime. So, make sure you use instanceof.




回答2:


You can do something like the following

    List<Animal> animalList = new ArrayList<Animal>();
    animalList.add(new Dog());
    animalList.add(new Cat());
    for(Animal animal : animalList) {
        if(animal instanceof  Dog) {
            System.out.println("Animal is a Dog");
        }
        else if(animal instanceof  Cat) {;
            System.out.println("Animal is a Cat");
        }
        else {
            System.out.println("Not a known animal." + animal.getClass() + " must extend class Animal");
        }
    }

You can also check for the class of the Animal and compare it with Animal sub classes. As in

for(Animal animal : animalList) {
    if(animal.getClass().equals(Dog.class)) {
        System.out.println("Animal is a Dog");
    }
    else if(animal.getClass().equals(Cat.class)) {;
        System.out.println("Animal is a Cat");
    }
    else {
        System.out.println("Not a known animal." + animal.getClass() + " must extend class Animal");
    }
}

In both cases you will get the outputs as

Animal is a Dog
Animal is a Cat

Basically both do the same thing. Just to give you better understanding.



来源:https://stackoverflow.com/questions/17779704/java-getting-the-subclass-from-a-superclass-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!