I am trying to learn Java generics. I am not clear when you will use <T extends Foo>
and when you will use <T super Foo>
. What do each one of these things mean about T? Lets say I have <T extends Comparable>
and <T super Comparable>
, what do each of these mean?
I've read several tutorials at sun.com but I'm still lost. Can somebody illustrate with examples?
super E> , it means "something in the super direction" as opposed to something in the extends direction.
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 .
The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.
The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type.
It depends which way on the inheritance hierarchy it allows. Assume you have a class "Child" which inherits from "Parent" which inherits from "Grandparent".
<T extends Parent>
accepts either Parent or Child while <T super Parent>
accepts either Parent or Grandparent.
There are three types of wildcards:
? extends Type
: Denotes a family of subtypes of type Type
. This is the most useful wildcard.? super Type
: Denotes a family of supertypes of type Type
.?
: Denotes the set of all types or any.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