隐式超级构造函数未定义Java泛型 [英] Implicit super constructor is undefined with Java Generics
问题描述
我有以下基类和子类:
public class BaseClass< T> {
public BaseClass(T value){
}
public class NewClass< T>扩展BaseClass< T> {
public NewClass(T值){
}
}
我得到以下错误:隐式超级构造函数BaseClass()未定义。必须明确地调用另一个构造函数
我该如何解决这个问题?
将您的子类cosntructor更改为:
public class NewClass< T>扩展BaseClass< T> {
public NewClass(T值){
super(value);
$ b $ p $如果你不添加 super(value);
,那么编译器会自动添加一个 super();
,它会链接到 0 -arg
超类的构造函数。基本上,你原来的子类构造函数被编译为:
public NewClass(T value){
super();
}
现在您可以看到它尝试调用 0-arg
超级构造函数,它是编译器无法找到的。为什么?由于在超类中,您提供了一个 1-arg
构造函数,因此编译器不会在其中添加任何默认构造函数。因此,这个错误。
你也可以通过在你的super中显式地使用 0-arg
构造函数来避免这个问题类,在这种情况下,您的原始子类代码将正常工作。
I have the following base class and sub class:
public class BaseClass<T> {
public BaseClass(T value){
}
public class NewClass<T> extends BaseClass<T> {
public NewClass(T value){
}
}
I get the following error: Implicit super constructor BaseClass() is undefined. Must explicitly invoke another constructor
How do I go about fixing this?
解决方案 Change your subclass cosntructor to:
public class NewClass<T> extends BaseClass<T> {
public NewClass(T value){
super(value);
}
}
If you don't add super(value);
, then compiler will automatically add a super();
, which will chain to a 0-arg
constructor of super class. Basically, your original subclass constructor is compiled to:
public NewClass(T value){
super();
}
Now you can see that, it tries to call 0-arg
super class constructor, which the compiler cannot find. Why? Since in super class, you have provided a 1-arg
constructor, compiler won't add any default constructor there. And hence that error.
You can also avoid this problem by giving an explicit 0-arg
constructor in your super class, in which case, your original sub class code will work fine.
这篇关于隐式超级构造函数未定义Java泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!