8

I have a confusion in following two method declarations:

    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    
    }

Shouldn't both of the above be valid? With the analogy of If U is parent of T , then T is child of U. Then why does 2nd one gives compilation error?

EDIT:: I think , T extends T and T super T both are valid. right ?

Priyank Doshi
  • 12,895
  • 18
  • 59
  • 82
  • I suspect `T extends U` means `T >= U` where `U super T` means `U < T`, but I could be wrong ... – user207421 Oct 03 '12 at 09:42
  • You should take a look at [this thread](http://stackoverflow.com/questions/1368166/what-is-a-difference-between-super-e-and-extends-e) – DayS Oct 03 '12 at 09:44
  • @DayS : Thats about ? - anything. I understand that. But whats in case of T and U ? – Priyank Doshi Oct 03 '12 at 09:46
  • possible duplicate of [Bounding generics with 'super' keyword](http://stackoverflow.com/questions/2800369/bounding-generics-with-super-keyword) – assylias Oct 03 '12 at 09:53

2 Answers2

7
  • Type parameters (your example) can only use extends (JLS #4.4):
TypeParameter:
    TypeVariable TypeBoundopt

TypeBound:
    extends TypeVariable
    extends ClassOrInterfaceType AdditionalBoundListopt

AdditionalBoundList:
    AdditionalBound AdditionalBoundList
    AdditionalBound

AdditionalBound:
    & InterfaceType
  • Wildcards can use either extends or super (JLS #4.5.1):
TypeArguments:
    < TypeArgumentList >

TypeArgumentList: 
    TypeArgument
    TypeArgumentList , TypeArgument

TypeArgument:
    ReferenceType
    Wildcard

Wildcard:
    ? WildcardBoundsopt

WildcardBounds:
    extends ReferenceType
    super ReferenceType
assylias
  • 321,522
  • 82
  • 660
  • 783
2

You can't bound a named generic with super. See also this stackoverflow posting.

Community
  • 1
  • 1
Tim Lamballais
  • 1,056
  • 5
  • 10