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 ?
super is a lower bound, and extends is an upper bound.
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 .
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.
TypeParameter:
TypeVariable TypeBoundopt
TypeBound:
extends TypeVariable
extends ClassOrInterfaceType AdditionalBoundListopt
AdditionalBoundList:
AdditionalBound AdditionalBoundList
AdditionalBound
AdditionalBound:
& InterfaceType
extends
or super
(JLS #4.5.1):TypeArguments:
< TypeArgumentList >
TypeArgumentList:
TypeArgument
TypeArgumentList , TypeArgument
TypeArgument:
ReferenceType
Wildcard
Wildcard:
? WildcardBoundsopt
WildcardBounds:
extends ReferenceType
super ReferenceType
You can't bound a named generic with super. See also this stackoverflow posting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With