Implicit super constructor is undefined with Java Generics [duplicate]

▼魔方 西西 提交于 2019-12-13 07:52:34

问题


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

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