Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aren't <U, T extends U> and <T, U super T> the same?

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 ?

like image 274
Priyank Doshi Avatar asked Oct 03 '12 09:10

Priyank Doshi


People also ask

What is the difference between List <? Super T and List <? Extends T?

super is a lower bound, and extends is an upper bound.

What does Super t mean?

super T denotes an unknown type that is a supertype of T (or T itself; remember that the supertype relation is reflexive). It is the dual of the bounded wildcards we've been using, where we use ? extends T to denote an unknown type that is a subtype of T .

What is super integer in Java?

super Integer> is a unbounded List that accepts any value that is a Integer or a superclass of Integer . The 2nd option is best used on the PECS Principle (PECS stands for Producer Extends, Consumer super). This is useful if you want to add items based on a type T irrespective of it's actual type.


2 Answers

  • 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
like image 179
assylias Avatar answered Nov 04 '22 17:11

assylias


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

like image 39
Tim Lamballais Avatar answered Nov 04 '22 16:11

Tim Lamballais