• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

"super" in Generics

 
Maleen Abeydeera
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While doing my own research, i got the following result.

class Animal<T extends Number> {} compiles, but
class Animal<T super Number> {) does not.

Is there any specific reason why?
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot use identifier syntax with super. You can only use ? with super.

The reason for this is that since you don't know what type it actually is, so you can't declare a name for it. Suppose you were allowed to do this

<T super Integer>

now what. What does T stands for?? It can be Number, Object, Comparable, Serializable (these are all super-types of Integer). So you are not sure what it actually is. So you cannot create instances of T as

T obj;

as you don't know the actual type of T. This is why you have to use the ? syntax.

Now you may ask why is this allowed for extends syntax.

<T extends Number>

In this case you at least know that T supports the functionality supported by Number. So you can say that yes, I can call intValue or shortValue on any object created of type T (as these methods are defined in Number). This is why identifier syntax is supported with extends but not super.
 
Maleen Abeydeera
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ankit. Great answer. Makes it look like it is really obvious.
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It didn't used to make sense for me either. I used to fear from Generics. Then everyone at ranch gave me the confidence that I can do it. I used generics tut from sun to get comfortable with Generics...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic