Java Generics: Delving into the 'Super' Keyword
Generics allow developers to write more flexible and reusable code by introducing type parameters. One aspect of generics is the use of the 'super' keyword in type bounds.
Super in Collection Declarations
When declaring a collection using a bounded wildcard with 'super', such as:
List<? super Number> list = null;
it specifies that the collection can hold elements whose type is a subtype of Number. However, this does not mean it can hold any supertype of Number. In this case, the following behavior is observed:
'Super' Keyword and Type Safety
Consider the following code:
static void test(List<? super Number> param) { param.add(new Integer(2)); } public static void main(String[] args) { List<String> sList = new ArrayList<String>(); test(sList); }
Intuitively, it seems like the code should compile since String is also a supertype of Number. However, it is not allowed due to type safety. Java enforces type safety to prevent runtime errors. Adding a String to a list that is declared to hold only subtypes of Number would violate type safety.
Why not '' Constructs?
Java does not allow type bounds with both 'super' and 'extends' keywords because it would lead to conflicting type constraints and make it difficult to ensure type safety. For example, if '' were allowed, and you declared List, it would be unclear whether 'S' is a subtype or a supertype of 'T'.
Key Considerations for 'super' in Generics
The above is the detailed content of How Does the `super` Keyword Affect Type Safety and Usage in Java Generics?. For more information, please follow other related articles on the PHP Chinese website!