Is there a difference between the generic bounds “Enum & Foo” and “Enum<? extends Foo>”

后端 未结 4 749
攒了一身酷
攒了一身酷 2020-12-09 10:35

Are these two (valid) generic bounds:

 & MyInterface>
>

4条回答
  •  情话喂你
    2020-12-09 10:49

    As others have pointed out, both syntaxes achieve the same bounds - and only because of the special case of enums, where we know the T in Enum must be the immediately extending enum type. So in restricting what T can be resolved to, there's no difference.

    There is a difference in the possible usage of instances of T, but it's probably such a nuance that it's irrelevant. Consider that the following statement compiles in MyIntersectionClass.use but not MyWildcardClass.use:

    T t2 = t.getDeclaringClass().newInstance();
    

    Only these will compile in the latter:

    MyInterface t2 = t.getDeclaringClass().newInstance();
    Enum t3 = t.getDeclaringClass().newInstance();
    

提交回复
热议问题