Generics wildcard instantiation

走远了吗. 提交于 2019-11-29 10:30:58

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

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

The idea is, when instantiating an object, the value for type parameters can be any non-wildcard type. ? extends B is a wildcard type, so it is disallowed. But X<? extends B> is not a wildcard type, though it has a wildcard type as a component. So you can say legally call new A<X<? extends B>>().

The rules makes sense if you think about it this way. Ultimately it is a byproduct of the more fundamental rule that a wildcard type like ? extends B cannot be the declared type of a field or variable. If A is defined as

class A<T> {
    T value;
}

then the hypothetical new A<? extends B>().value would be a field declared of type ? extends B. Since that is illegal, so is the instantiation. But new A<X<? extends B>>() does not have that problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!