List<? extends ParentClass>
is a list of some specific subtype of ParentClass
. Since, it's not know what exact specific subtype it is, the compiler won't let you add any object to it.
For starters, it's easy to mistake it with any subtype of ParentClass
and wonder why they can't add the instances of the subtypes.
For instance, suppose you have a following class hierarchy -
class P { }
class A extends P { }
class B extends P { }
Now if you declare a a list as follows -
List<? extends P> l = ...;
it means l
is a list of some specific subtype of P
, which could be either A
or B
(or even P
itself), but the compiler doesn't know exactly which one. So, you can't add anything to it, because the chance is that you could be adding an instance of B
to a list of A
s creating some heap pollution.
You would declare such a list when you are only interested in reading the elements of list as P
's instances.