Java泛型练习

1.以下语句正确的是:(多选):AB

A. List list=new ArrayList();
B. List list=new ArrayList<>();
C. 已知Cat是Animal类的子类,则List list=new ArrayList();
D. List list=new ArrayList();
 
  

2.通过练习,掌握泛型作为方法参数的应用,具体内容见任务要求。运行效果如下:
Java泛型练习_第1张图片
Java泛型练习_第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 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 DogList = new ArrayList();
		DogList.add(d1);
		DogList.add(d2);
		List CatList = new ArrayList();
		CatList.add(c1);
		CatList.add(c2);
		AnimalPlay ap = new AnimalPlay();
		ap.play(DogList);
		ap.play(CatList);
	}
}

Java泛型练习_第3张图片

你可能感兴趣的:(Java泛型练习)