Home  >  Article  >  Java  >  How Does the `super` Keyword Affect Type Safety and Usage in Java Generics?

How Does the `super` Keyword Affect Type Safety and Usage in Java Generics?

Linda Hamilton
Linda HamiltonOriginal
2024-11-25 14:24:11144browse

How Does the `super` Keyword Affect Type Safety and Usage in Java Generics?

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:

  • list.add(new Integer(0)) compiles and works correctly. Integer is a subtype of Number, so it can be added to the list.
  • list.add(new Object()) does not compile. Object is a supertype of Number, but the list is not declared to hold supertypes of Number.

'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

  • Bounded wildcards with 'super' capture subtypes of the specified type.
  • Type safety dictates that elements added to super-bounded collections must be subtypes of the specified type.
  • 'super' and 'extends' cannot be combined in type bounds due to potential type safety violations.

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!

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