Generics super vs. extends

后端 未结 4 863
情书的邮戳
情书的邮戳 2020-12-30 16:23

Just when I thought I finally understood generics, I came across the following example:

public class Organic {
          void react(E e) { }
            


        
4条回答
  •  星月不相逢
    2020-12-30 16:52

    Your first declaration

    Organic compound
    

    means that compound could be an Organic (since Aliphatic extends Organic, Hexane extends Aliphatic and SomeSubtypeOfHexane extends Hexane).

    In that case, compound.react(new Organic()), compound.react(new Aliphatic()) and compound.react(new Hexane()) would lead to a type error, since E in compound must be a SomeSubtypeOfHexane (or subtype thereof).


    Your second declaration

    Organic compound
    

    means that compount could be an Organic.

    In that case compound.react(new Organic()) would lead to a type error, since E must be an Aliphatic (or subtype thereof).


    Remember that declaring a variable using A or A

    • extends the amount of objects that can be assigned to it, and, in consequence,
    • restricts what can be done with the variable.

    Since the exact type of the class is unknown (only a constraint is known), the compiler has to err on the side of safety and disallow certain operations that are either not co- or contravariant. (If you are not already familiar with it, Co- and contravariance is the scientific background of these types of generics.)

提交回复
热议问题