问题
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?
回答1:
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.
回答2:
if it asks to explicitly invoke another constructor, just do it:
public class NewClass<T> extends BaseClass<T> {
public NewClass(T value){
super(value);
}
}
来源:https://stackoverflow.com/questions/18954944/implicit-super-constructor-is-undefined-with-java-generics