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

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

Are these two (valid) generic bounds:

 & MyInterface>
>

相关标签:
4条回答
  • 2020-12-09 10:49

    In this specific case there is no difference because Enums formal type parameter is effectively the self type. This is because one can not inherit from Enum like so:

    class MyEnumA extends Enum<MyEnum2> {}
    class MyEnumB implements MyInterface {}
    

    So yes, semantically they're the same bound, but only because it's Enum.

    0 讨论(0)
  • 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<T> 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<? extends MyInterface> t3 = t.getDeclaringClass().newInstance();
    
    0 讨论(0)
  • 2020-12-09 10:55

    Since the second one relies on the special fact that Java enums are implemented as MyEnum extends Enum<MyEnum>, I would prefer the first one, which doesn't rely an such assumptions and states your constraints explicitly.

    0 讨论(0)
  • 2020-12-09 11:10

    They'll do the same thing, but I would say T extends Enum<? extends MyInterface> is a bit more standard and thus better, if only because it's more commonly and quickly recognizable. Many people don't even know about the & part of generics.

    You could also argue that they read slightly differently. T extends Enum<T> & MyInterface I would read as "an enum which also happens to be a MyInterface." T extends Enum<? extends MyInterface> I would read as "an enum that implements MyInterface." So to that extent, it's a matter of personal preference; I prefer the latter.

    0 讨论(0)
提交回复
热议问题