我有以下代码:
public class A {}
public class B extends A {}
public class C <T extends A> {
private final T data;
public C(final T data) {
this.data = data;
}
}
public class D<T extends B> extends C<T> {
public D(T data) {
super(data);
}
public D() {
this(new B());
}
public static D<B> create() {
return new D(new B());
}
}
D类存在编译错误:
error: no suitable constructor found for D(B)
this(new B());
constructor D.D() is not applicable
(actual and formal argument lists differ in length)
constructor D.D(T) is not applicable
(actual argument B cannot be converted to T by method invocation conversion)
where T is a type-variable:
T extends B declared in class D
令我困惑的是,基本相同的静态方法 D.create() 编译时没有任何错误。谁能解释这个错误?还有D()和D.create()的区别?
最佳答案
错误是因为对于 D
类,不知道类型将是 B
,只知道泛型类型将扩展 B
- 你假设它会是 B
因为你的类层次结构中(还)没有其他类(编译器必须考虑的一个事实可能会在未来改变).
请注意,在工厂方法中,您正在为 D
(没有通用参数的类型)实例化 raw 类型。相反,提供一个类型:
你应该改变:
public static D<B> create() {
return new D(new B());
}
到:
public static D<B> create() {
return new D<B>(new B()); // Note: Added generic parameter <B>
}
关于Java泛型类构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20218337/