Polymorphic set parameters

How array parameters are polymorphic:

  • Ordinary array
public class TestGenericsl{

	public void takeAnimals(Animal[] animals){//方法的参数为animal[] 
		for(Animal a : animals){
			a.eat();//所以后面只能使用的animal方法
		}
	}
	public static void main(){
		new TestGenericsl().go();
	}
	public void go(){
		Animal[] animals = {new Dog(),new Cat(),new Dog()};//有猫有狗
		Dog[] dogs = {new Dog(),new Dog(),new Dog()};
		takeAnimals(animals);
		takeAnimals(dogs);
		//传入的dogs[]数组是animal[]数组的子类,这就是多态(把子类对象当作父类来看)
	}
}
  • Dynamic array ArrayList
public void go(){
	ArrayList<Animal> animals = new ArrayList<Animal>();
	animals.add(new Dog());
	animals.add(new Cat());
	animals.add(new Dog());
	takeAnimals(animals);
	
	ArrayList<Dog> dogs = new ArrayList<Dog>();
	dogs.add(new Dog());
	dogs.add(new Dog());
	takeAnimals(dogs);
}

public void takeAnimals(ArrayList<Animal> animals){
	for(Animal a : animals){
		a.eat();
	}
}

This code gives an error at compile time, because the method declaration is animal [] array, it will only take animal [] parameter, neither dog array nor cat array. Why can ordinary arrays do?

Strictly speaking, ordinary digital parameters are not really polymorphic. This is because the type of the array is checked during runtime, and the type check of the collection will only happen during compilation.

We use animal [] as an array parameter, just to be able to put all animal elements, but the above cannot be achieved.

At this time, you need wild characters >, That is, polymorphic set parameters.

public void takeAnimals(ArrayList<? extends Animal> animals){//extends 代表继承或者实现,也就是说extends 或 implements皆可
	for(Animal a : animals){
		a.eat();
	}
}
Published 27 original articles · praised 2 · visits 680

Guess you like

Origin blog.csdn.net/qq_44273739/article/details/104525468