相关疑难解决方法(0)

子类构造函数 - 为什么子类构造函数必须存在默认构造函数?

给出一个随机类:

public class A<T> {
    public T t;

    public A () {}  // <-- why is this constructor necessary for B?
    public A (T t) {
        this.setT(t);
    }
    public T getT () {
        return this.t;
    }
    protected void setT (T t) {
        this.t = t;
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

还有一个扩展课程:

public class B extends A<Integer> {
    public B (Integer i) {
        this.setT(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么B要求A有空构造函数?我原以为它会想要使用类似的构造函数而不是默认的构造函数.我尝试编译没有默认的构造函数,但没有它我得到以下消息...

java.lang.NoSuchMethodError: A: method <init>()V not found at B.<init>
Run Code Online (Sandbox Code Playgroud)

谁能解释为什么会这样?

java constructor subclass

3
推荐指数
2
解决办法
1万
查看次数

标签 统计

constructor ×1

java ×1

subclass ×1