Home > Java > javaTutorial > How Do Java Generics\' `? super` Wildcards Work and What Are Their Limitations?

How Do Java Generics\' `? super` Wildcards Work and What Are Their Limitations?

DDD
Release: 2024-11-25 06:17:16
Original
634 people have browsed it

How Do Java Generics' `? super` Wildcards Work and What Are Their Limitations?

Java Generics Super Keyword

Understanding Bounded Wildcards

When we use bounded wildcards with super, it means that the type parameter can be the specified type or any of its superclass. For example, List indicates that the list can hold objects of type Number or any of its parent classes.

Adding Elements to Bounded Wildcards

In your first example, the list list declared as List cannot take an Object because Object is not a subclass of Number. On the other hand, Integer is a subclass of Number, so it can be added to the list.

Compilation Errors with Super Keyword

In your second example, you attempted to pass a List to a method that expects a List. This compilation error occurs because String is not a subclass of Number. The logic you presented is incorrect: Object is not superclass of Number and String is not subclass of Number.

RESTRICTIONS ON WILDCARDS

Unlike lower bounded wildcards, upper bounded wildcards cannot be used as producers. This means that you cannot obtain individual elements from a List. This restriction exists to prevent type safety violations.

Conclusion

Bounded wildcards with super allow us to create collections that can consume objects of multiple types that inherit from a common superclass. However, we should be careful when adding elements to these collections, as we cannot add objects that are not subclasses of the designated superclass.

The above is the detailed content of How Do Java Generics\' `? super` Wildcards Work and What Are Their Limitations?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template