Subclass constructors - Why must the default constructor exist for subclass constructors?

我怕爱的太早我们不能终老 提交于 2019-12-10 10:18:16

问题


Given a random class:

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;
    }
}

And an extended class:

public class B extends A<Integer> {
    public B (Integer i) {
        this.setT(i);
    }
}

Why does B require A to have the empty constructor? I would have assumed it would want to use the similar constructor instead of the default constructor. I tried compiling without the default constructor, but I get the following message without it...

java.lang.NoSuchMethodError: A: method <init>()V not found at B.<init>

Can anyone explain why this is?


回答1:


The important point is to understand that the first line of any constructor is to call the super constructor. The compiler makes your code shorter by inserting super() under the covers, if you do not invoke a super constructor yourself.

Also if you do not have any constructors an empty default constructor - here A() or B() - would automatically be inserted.

You have a situation where you do not have a super(...) in your B-constructor, so the compiler inserts the super() call itself, but you do have an A-constructor with arguments so the the default A()-constructor is not inserted, and you have to provide the A()-constructor manually, or invoke the A(i)-constructor instead. In this case, I would suggest just having

public class B extends A<Integer> {
    public B (Integer i) {
        super(i);
    }
}



回答2:


You may use your own constructor in A, but you have to call it explicitly from the B's constructor, e.g.:

public B(Integer i) {
  super(i);
  ...
}

If you don't do that, the compiler will attempt to instantiate A itself, by calling its default constructor.




回答3:


If you don't make a call to a super constructor using super(i) as the first line of your constructor it will implicitly call the default super constructor



来源:https://stackoverflow.com/questions/9370520/subclass-constructors-why-must-the-default-constructor-exist-for-subclass-cons

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