1.以下语句正确的是:(多选):AB
A. List<String> list=new ArrayList<String>();
B. List<Integer> list=new ArrayList<>();
C. 已知Cat是Animal类的子类,则List<Animal> list=new ArrayList<Cat>();
D. List<Object> list=new ArrayList<Integer>();
2.通过练习,掌握泛型作为方法参数的应用,具体内容见任务要求。运行效果如下:
public abstract class Animal {
//名字
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void play();
}
public class Dog extends Animal {
@Override
public void play() {
System.out.println("小狗" + this.getName() + "在做游戏!");
}
public Dog() {
}
public Dog(String name) {
this.setName(name);
}
}
public class Cat extends Animal {
@Override
public void play() {
System.out.println("小猫" + this.getName() + "在做游戏!");
}
public Cat() {
}
public Cat(String name) {
this.setName(name);
}
}
import java.util.List;
public class AnimalPlay {
public void play(List<? extends Animal> animal) {
for(int i = 0;i < animal.size();i++) {
Animal a = animal.get(i);
a.play();
}
}
}
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
Dog d1 = new Dog("巴迪");
Dog d2 = new Dog("豆豆");
Cat c1 = new Cat("花花");
Cat c2 = new Cat("凡凡");
List<Dog> DogList = new ArrayList<Dog>();
DogList.add(d1);
DogList.add(d2);
List<Cat> CatList = new ArrayList<Cat>();
CatList.add(c1);
CatList.add(c2);
AnimalPlay ap = new AnimalPlay();
ap.play(DogList);
ap.play(CatList);
}
}