Class<? extends Integer>
will compile fine, but Integer
is a final type so it doesn't make sense to use it as an upper bound (nothing will ever extend
it).
If you try to use a final type as an upper bound for a type parameter, you will get a compiler warning:
The type parameter T should not be bounded by the final type Integer. Final types cannot be further extended
Why would using a final type as an upper bound for a wildcard be perfectly fine, but throw a warning for a type parameter? Why does Java even allow for wildcards to be bounded by a final upper type?
A bounded wildcard is one with either an upper or a lower inheritance constraint. The bound of a wildcard can be either a class type, interface type, array type, or type variable. Upper bounds are expressed using the extends keyword and lower bounds using the super keyword.
The difference is on the compiler side. On the first one you can use the type (to cast something or use it as a bound to call another method for example) while on the second one, you cannot use it.
A lower bounded wildcard is expressed using the wildcard character ('? '), following by the super keyword, followed by its lower bound: <? super A>. Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.
Upper-bound is when you specify (? extends Field) means argument can be any Field or subclass of Field. Lower-bound is when you specify (? super Field) means argument can be any Field or superclass of Field. Try following code: Uncomment the code and check if any error comes.
Class<Integer>
is not as permissive for assignment as Class<? extends Integer>
.
For example, this compiles:
Class<? extends Number> numberClass = Integer.class;
Class<? extends Integer> integerClass = numberClass.asSubclass(Integer.class);
This doesn't:
Class<? extends Number> numberClass = Integer.class;
Class<Integer> integerClass = numberClass.asSubclass(Integer.class);
Myself, I couldn't get a compiler warning as you do (perhaps you could provide an example and details on your compiler?).
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