wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark ""super" in Generics" Watch ""super" in Generics" New topic
Author

"super" in Generics

Maleen Abeydeera
Greenhorn

Joined: Nov 10, 2008
Posts: 20
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

Joined: Aug 03, 2008
Posts: 9321
    
  17

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.


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Maleen Abeydeera
Greenhorn

Joined: Nov 10, 2008
Posts: 20
Thanks Ankit. Great answer. Makes it look like it is really obvious.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9321
    
  17

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...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: "super" in Generics