我是 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*/ );
}
}
1)有没有办法从 Aminal 列表中获取 Dog 或 Cat 实例?2)如果是,我应该如何正确构建 getCertainAnimals 方法?