Home  >  Article  >  Java  >  Why can\'t the \'super\' keyword be used to bound type parameters in Java generics?

Why can\'t the \'super\' keyword be used to bound type parameters in Java generics?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 09:21:02844browse

Why can't the 'super' keyword be used to bound type parameters in Java generics?

Bounding Generics with the 'super' Keyword: A Detailed Explanation

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:

  • Generics and arrays: Generics and arrays have inherent limitations, and they do not intermix seamlessly.
  • Alternatives to using 'super': To achieve type safety in such scenarios, it is recommended to use wildcards or method overloading instead of bounding type parameters with 'super'.

Related Resources:

  • Java Tutorials/Generics

    • Subtyping
    • More fun with wildcards
  • Java Generics: What is PECS? (Producer extends consumer super)
  • What is the difference between super and extends in Java 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn