Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic lower bound to Object

Tags:

java

generics

It is possible to code a generic parameter bound as:

public <T super Object> void someMethod(T t);

Is there a valid usage of such a bound?

like image 436
Bohemian Avatar asked Nov 17 '25 14:11

Bohemian


2 Answers

According to the JLS http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.4 a type parameter (The < T extends Object > term) consists out of:

TypeParameter:
    TypeVariable TypeBound*

TypeBound:
    extends TypeVariable
    extends ClassOrInterfaceType AdditionalBoundList*

AdditionalBoundList:
    AdditionalBound AdditionalBoundList
    AdditionalBound

AdditionalBound:
    & InterfaceType

* = optional

You see the TypeBound, there is only the usage of extends specified. Unfortunately, a lower bound type parameter, using super, is not specified. A lower bound is only specified in the wildcard usage (JLS#4.5.1)

Good question, that got me digging in the JLS, and I don't know why this not implemented in java, it is just not specified.

like image 117
burna Avatar answered Nov 19 '25 05:11

burna


Such a lower bond is totally useless. If you want to have a template that can only accept the Object, all you have to do is to remove all the generic template and code directly your class using the Object as your type.

For other types than Object, it doesn't make any sense neither. Why would you want of a template that would accept object of type A or objects without the type A (Object for example) but that would refuse object of type B when B is a subclass of A? It's totally illogical.

Same thinking with the interface: you would accept any types that don't implement an interface I at all or that implement it but you would refuse a type that not only have the interface I but have extended it???

like image 26
SylvainL Avatar answered Nov 19 '25 07:11

SylvainL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!