Hello,
I am studying for the SCJP. While doing that I encountered a problem which is very strange. I solved it, but I still don't know why it didn't work. Using the code below, it works due to the type definition for the class: <T extends Animal>, but it shouldn't (according to my understanding that is...). But removing <T extends Animal> makes the program behave as I expect, with appropriate errors which is that the compiler complains that I can not send List<Dog> and List<Cat> to checkAnimals(List<Animal>). How come that it works using the <T extends Animal>. I am not using T anywhere in the program so I thought it wouldn't have any influence at all.
import java.util.ArrayList;
import java.util.List;
public class AnimalDoctorGenerics <T extends Animal>{
public void checkAnimals(List<Animal> animals){
for(Animal a: animals){
System.out.println(a);
}
}
public static void main(String[] args) {
List<Dog> dogs = new ArrayList<Dog2();
dogs.add(new Dog());
dogs.add(new Dog());
List<Cat> cats = new ArrayList<Cat>();
cats.add(new Cat());
cats.add(new Cat());
AnimalDoctorGenerics docs = new AnimalDoctorGenerics();
docs.checkAnimals(dogs);
docs.checkAnimals(cats);
}
}
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
Thanks in advance!
Regards,
Niklas