Your first ad
Organic<? extends Organic> compound
means that compound can be Organic<SomeSubtypeOfHexane> (because Aliphatic extends Organic , Hexane extends Aliphatic and SomeSubtypeOfHexane extends Hexane ).
In this case, compound.react(new Organic()) , compound.react(new Aliphatic()) and compound.react(new Hexane()) will result in a type error, since E in compound must be SomeSubtypeOfHexane (or its subtype) .
Your second ad
Organic<? super Aliphatic> compound
means compount can be Organic<Aliphatic> .
In this case, compound.react(new Organic()) will result in a type error, since E must be Aliphatic (or its subtype).
Remember that declaring a variable with A<? extends B> A<? extends B> or A<? super B> A<? super B>
- expands the number of objects that can be assigned to him, and therefore
- limits what can be done with a variable.
Since the exact type of the class is unknown (only the restriction is known), the compiler should be wrong on the security side and prohibit certain operations that are either not covariant or contravariant. (If you are not already familiar with it, Co- and contravariance is the scientific basis for these types of generics.)
source share