In the code below I was surprised that I couldn't add an Animal to the List at the line indicated in the comment.
Can anyone clarify the rules here? From what I could see it is legal to pass any kind of list of objects where these objects are Dogs or supertypes of Dog, but it is only legal to add an actual Dog to the list.
So where we say ? super <class> can I assum the general rule that I can only add <class> objects to the collection even though the collection may be typed on a super type?
Or has something else gone wrong?
Joined: Dec 28, 2006
public void addAnimal2(List<? super Dog> animals)
For this function declaration, you can pass Dog or any of its super types. But inside the function you can add only Dog or its subtypes.
SCJP 1.5<br />SCWCD 1.4
Joined: Oct 23, 2006
why animals.add(new Animal()) is not allowed ?
if animals is pointing to new ArrayList<Dog>() and try to add new Animal() will lead to run time exception. only lower bound class object only can be added in the animals reference.