I wonder why does this piece of code compile successfully?
Source code:
abstract class A<K extends Number>
{
public abstract <M> A<? super M> useMe(A<? super M> k);
}
Compiled successfully
How does it work and why does this compile? M is any type, so why it can be used?. Should it be: <M extends Number>
?
This will not compile:
abstract class A<K extends Number>
{
public abstract <M> A<? super M> useMe(A<M> k);
}
Error message:
type argument M is not within bounds of type variable K where M, K are type variables: M extends Object declared in method useMe(A) K extends Number declared in class A
What is the difference?
Java generics lower bounded wildcard : Lower bounded wildcard is used to restrict the unknown type to be a specific type or a super type of that type using ‘?’ with super keyword.
Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both. Say you want to write a method that puts Integer objects into a list.
A wildcard can have only one bound, while a type parameter can have several bounds. A wildcard can have a lower or an upper bound, while there is no such thing as a lower bound for a type parameter. Wildcard bounds and type parameter bounds are often confused, because they are both called bounds and have in part similar syntax. […]
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.
This compiler behavior was discussed on this Eclipse bug. Originally, the Eclipse compiler did error for the expression in your example, while javac did not. Although I haven't yet searched the JLS directly, the consensus seems to be that there is nothing in the spec requiring lower bounded wildcards to be checked against type parameter bounds. In this situation it's ultimately left to the caller to assign a type that satisfies the constraints (as surmised by Stephan Herrmann on that post).
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