Question: Why can't the 'super' keyword be used to bound type parameters, unlike wildcards?
Answer:
Bounding a type parameter with 'super' (e.g., '') is disallowed in Java because it would effectively have negligible impact on the type bound and would not serve its intended purpose.
Consider the following hypothetical code:
interface Collection<T> { <S super T> S[] toArray(S[] a); }
This code proposes that the 'toArray' method in the 'Collection' interface should have a type parameter 'S' that is a supertype of 'T'. However, this bound would be meaningless because every type is a supertype of 'Object', and since an array of any reference type can be cast to an 'Object[]', the compiler would allow any array to be passed as an argument to 'toArray', regardless of whether it is an intended subtype.
Therefore, using 'super' to bound type parameters would not prevent runtime errors, such as 'ArrayStoreException'. As such, it is not allowed in Java's type system.
Example:
Consider a hypothetical generic method:
<T super Integer> void add(T number)
This method intends to allow adding 'integers,' 'numbers,' and 'objects' (as they are all superclasses of 'Integer') but disallow 'strings' as they are not. However, since 'Object' is a superclass of 'Integer,' 'strings' can still be added due to implicit casting, leading to potential runtime errors.
Additional Considerations:
Related Resources:
Java Tutorials/Generics
The above is the detailed content of Why can't the 'super' keyword be used to bound type parameters in Java generics?. For more information, please follow other related articles on the PHP Chinese website!