子类构造函数 - 为什么必须为子类构造函数存在默认构造函数? [英] Subclass constructors - Why must the default constructor exist for subclass constructors?

查看:140
本文介绍了子类构造函数 - 为什么必须为子类构造函数存在默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个随机类:

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

和一个扩展类:

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

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

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?

推荐答案

重要的一点是要理解任何构造函数的第一行是调用超级构造函数。如果你不自己调用一个超级构造函数,编译器通过插入 super()来缩短你的代码。

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.

此外,如果您没有任何构造函数为空的默认构造函数 - 这里 A() B() - 会自动插入。

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

super(...)在你的B构造函数中,所以编译器插入 super()你有一个具有参数的A构造函数,所以默认的A() - 构造函数不会被插入,你必须手动提供A() - 构造函数,或调用A(i)构造函数。在这种情况下,我建议只有

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

这篇关于子类构造函数 - 为什么必须为子类构造函数存在默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆