2

I'm doing a deeper study on Java generics and trying some edge cases just to test my understanding. Compare these class declarations:

class C<T extends Number> { // this works

class C<T super Number> { // this doesn't

Why can't I declare a generic class with <T super Number>?

JohnDoDo
  • 4,720
  • 8
  • 31
  • 47

3 Answers3

0

you can't use "super" in a class declaration

Why? Because such construction doesn't make sense. For example, you can't erase the type parameter with Vehicle because the class Forbidden could be instantiated with Object. So you have to erase type parameters to Object anyway. If think about class Forbidden, it can take any value in place of X, not only superclasses of Vehicle. There's no point in using super bound, it wouldn't get us anything. Thus it is not allowed.

see http://onewebsql.com/blog/generics-extends-super

Leo
  • 6,480
  • 4
  • 37
  • 52
-1

The <...> part next to a class identifier is a type parameter list. In it you declare type variables. The Java Language Specification has specific rules about what a type variable is. Those are described here.

TypeParameter:
    TypeVariable TypeBoundopt

TypeBound:
    extends TypeVariable
    extends ClassOrInterfaceType AdditionalBoundListopt

AdditionalBoundList:
    AdditionalBound AdditionalBoundList
    AdditionalBound

AdditionalBound:
    & InterfaceType

In other words, you cannot use the super keyword in a type parameter.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
-1

The keyword extends is used to specify the upper bound for type T; with this, only the classes or interfaces implementing the interface Number can be used as a replacement for T. Note that the extends keyword is used for any base type—irrespective of if the base type is a class or an interface.