I am just trying to understand the extends
keyword in Java Generics.
List<? extends Animal>
means we can stuff any object in the List
which IS A Animal
then won't the following also mean the same thing:
List<Animal>
Can someone help me know the difference between the above two? To me extends
just sound redundant here.
Thanks!
Best Answer
List<Dog>
is a subtype ofList<? extends Animal>
, but not a subtype ofList<Animal>
.Why is
List<Dog>
not a subtype ofList<Animal>
? Consider the following example:If you were allowed to pass a
List<Dog>
to this function, you would get a run-time error.EDIT: Now, if we use
List<? extends Animal>
instead, the following will happen:You could pass a
List<Dog>
to this function, but the compiler realizes that adding something to the list could get you into trouble. If you usesuper
instead ofextends
(allowing you to pass aList<LifeForm>
), it's the other way around.The theory behind this is Co- and Contravariance.