Java:从超类列表中获取子类

use*_*421 6 java subclass superclass

我是java新手,对以下代码有2个问题:

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*/ );
  }
}
Run Code Online (Sandbox Code Playgroud)

1)有没有办法从Aminal列表中获取Dog或Cat实例?2)如果是,我应该如何正确构建getCertainAnimals方法?

Ste*_* P. 4

Animal a = animals.get(i);   

if  (a instanceof Cat)
{
    Cat c = (Cat) a;
} 
else if (a instanceof Dog)
{
    Dog d = (Dog) a;
} 
Run Code Online (Sandbox Code Playgroud)

注意:如果您不使用 ,它将编译instanceof,但它也允许您转换aCator Dog,即使aRat。尽管进行了编译,您仍将获得ClassCastException运行时。所以,请确保您使用instanceof.