Create generics wildcards

I was looking through another code the other day, and I came across a line that was causing some concern. To simplify, let's say I have a common class A and an abstract class B. Is the following instantiation allowed, and if so, why?

Object obj = new A<? extends B>(); 

I personally have never seen an instance as above, although an ad like

 A<? extends B> obj = null; 

certainly will be. I have always used a wildcard in generics to declare method parameters, so I may just not have experience.

+6
source share
1 answer

Actually new A<? extends B>() new A<? extends B>() does not compile. It has been consistently illegal since Java 5.

But I assume that your original example was something like new A<X<? extends B>>() new A<X<? extends B>>() . The latter is legal in recent versions of Java.

The idea is that when creating an instance of the object, the value for the type parameters can be any asymmetric type. ? extends B ? extends B is a wildcard type, so it is not allowed. But X<? extends B> X<? extends B> not a wildcard type, although it has a wildcard as a component. So you can say legally calling new A<X<? extends B>>() new A<X<? extends B>>() .

Rules make sense if you think of it this way. Ultimately, this is a byproduct of a more fundamental rule, what is the type of a wildcard type ? extends B ? extends B cannot be a declared field or variable type. If A is defined as

 class A<T> { T value; } 

then hypothetical new A<? extends B>().value new A<? extends B>().value will be a field declared of type ? extends B ? extends B Because it is illegal, as well as instantiation. But new A<X<? extends B>>() new A<X<? extends B>>() does not have this problem.

+3
source

Source: https://habr.com/ru/post/927101/


All Articles