Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Strange behavior using generics classes

843793Jun 15 2009 — edited Jun 16 2009
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 14 2009
Added on Jun 15 2009
6 comments
253 views