Jeffrey
Jeffrey

Reputation: 44798

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?

Upvotes: 9

Views: 722

Answers (1)

Mark Peters
Mark Peters

Reputation: 81054

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

Upvotes: 5

Related Questions