Home > Java > javaTutorial > Why Aren\'t Java Generics Covariant?

Why Aren\'t Java Generics Covariant?

Linda Hamilton
Release: 2024-11-21 04:19:10
Original
904 people have browsed it

Why Aren't Java Generics Covariant?

Java Generics Covariance

In Java, generics are not covariant, as explained in the provided article. This means that if a class extends a generic class, the child class's generic type cannot be a subtype of the parent class's generic type.

Understanding the "Alias" Concept

The author mentions that "if ln were aliased with li," it would break the type-safety promise. An alias refers to an alternative name or reference to an object. In this scenario, li is an alias of ln.

An Illustrative Example

Consider the following code:

List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li; // illegal
ln.add(new Float(3.1415));
Copy after login

Although Integer inherits from Number, adding a Float object to ln is illegal. This is because, by aliasing li to ln, we are essentially saying that li can hold Numbers. However, li was originally declared to hold only Integers. Therefore, adding a Float to ln violates the type-safety guarantee of li.

Conclusion

This example demonstrates that generics are not covariant in Java. Attempting to assign a subclass's generic type to a superclass's generic type will result in a compile-time error.

The above is the detailed content of Why Aren\'t Java Generics Covariant?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template