Here's my understanding.
Suppose we have a generic type with 2 methods
type L<T>
T get();
void set(T);
Suppose we have a super type P
, and it has sub types C1, C2 ... Cn
. (for convenience we say P
is a subtype of itself, and is actually one of the Ci
)
Now we also got n concrete types L<C1>, L<C2> ... L<Cn>
, as if we have manually written n types:
type L_Ci_
Ci get();
void set(Ci);
We didn't have to manually write them, that's the point. There are no relations among these types
L<Ci> oi = ...;
L<Cj> oj = oi; // doesn't compile. L<Ci> and L<Cj> are not compatible types.
For C++ template, that's the end of story. It's basically macro expansion - based on one "template" class, it generates many concrete classes, with no type relations among them.
For Java, there's more. We also got a type L<? extends P>
, it is a super type of any L<Ci>
L<Ci> oi = ...;
L<? extends P> o = oi; // ok, assign subtype to supertype
What kind of method should exist in L<? extends P>
? As a super type, any of its methods must be hornored by its subtypes. This method would work:
type L<? extends P>
P get();
because in any of its subtype L<Ci>
, there's a method Ci get()
, which is compatible with P get()
- the overriding method has the same signature and covariant return type.
This can't work for set()
though - we cannot find a type X
, so that void set(X)
can be overridden by void set(Ci)
for any Ci
. Therefore set()
method doesn't exist in L<? extends P>
.
Also there's a L<? super P>
which goes the other way. It has set(P)
, but no get()
. If Si
is a super type of P
, L<? super P>
is a super type of L<Si>
.
type L<? super P>
void set(P);
type L<Si>
Si get();
void set(Si);
set(Si)
"overrides" set(P)
not in the usual sense, but compiler can see that any valid invocation on set(P)
is a valid invocation on set(Si)