8

我对以下两个方法声明感到困惑:

    private <U, T extends U> T funWorks(T child, U parent) {
      // No compilation errors
    }

    private <T, U super T> T funNotWorks(T child, U parent) {
      // compilation errors    
    }

以上两个都不应该有效吗?类比 如果 U 是 T 的父级,则 T 是 U 的子级。那为什么第二个会出现编译错误?

编辑:: 我认为,T extends T两者T super T都是有效的。对 ?

4

2 回答 2

7
  • 类型参数(您的示例)只能使用扩展(JLS #4.4):
TypeParameter:
    TypeVariable TypeBoundopt

TypeBound:
    extends TypeVariable
    extends ClassOrInterfaceType AdditionalBoundListopt

AdditionalBoundList:
    AdditionalBound AdditionalBoundList
    AdditionalBound

AdditionalBound:
    & InterfaceType
  • 通配符可以使用extendssuperJLS #4.5.1):
TypeArguments:
    < TypeArgumentList >

TypeArgumentList: 
    TypeArgument
    TypeArgumentList , TypeArgument

TypeArgument:
    ReferenceType
    Wildcard

Wildcard:
    ? WildcardBoundsopt

WildcardBounds:
    extends ReferenceType
    super ReferenceType
于 2012-10-03T09:46:23.867 回答
2

您不能将命名泛型与 super 绑定。另请参阅stackoverflow 帖子。

于 2012-10-03T09:45:33.677 回答