Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard with final upper bound

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?

like image 475
Jeffrey Avatar asked Aug 11 '12 21:08

Jeffrey


People also ask

What is a bounded wildcard?

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.

What are the key differences between upper bounded wildcard and lower bounded wildcard?

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.

Which syntax is used to express a wildcard with a lower bound?

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.

What does upper bound mean in Java?

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.


1 Answers

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?).

like image 162
Mark Peters Avatar answered Sep 22 '22 04:09

Mark Peters