2012-10-03 42 views
8

我有以下兩種方法聲明一個困惑:是不是<U,T擴展U>和<T,U super T>一樣?

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 TT super T都是有效的。對 ?

+0

我懷疑'T延伸U'意思是'T> = U'其中'U super T'意思是'U EJP

+0

你應該看看[this thread](http://stackoverflow.com/questions/) 1368166/what-is-a-difference-between-super-e-and-extends-e) – DayS

+0

@DayS:那是關於什麼的? - 什麼。我明白那個。但是T和U的情況如何? –

回答

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 
2

你不能用super綁定一個命名泛型。另請參閱this stackoverflow發佈。

相關問題