java - 不允许在调用 super 构造函数时使用实例变量和方法

标签 java constructor

为什么实例变量和方法不允许调用 super 构造函数或重载构造函数?

最佳答案

因为当你调用 super 构造函数时,就是构建父类。由于类层次结构,在构建父类时尚未构建子类。我们用一个例子来说明一下

class Parent() {
    protected String s;
    public Parent(String s) {
        System.out.println("parent created with "+s);
        this.s = s; // don't do this at home, kids, one letter variables stinks like hell
    }
}

class Child extends Parent {
    public Child(String s) {
        // don't try to put an instruction here, it's impossible due to the mandatory call to super as first instruction
        super(s);
        System.out.println("child created with "+s);
    }
}

当你调用new Child("I'm the king of the world")时,调用的第一个方法实际上是Parent(String),因为System.out将显示出来。这很正常,因为 ChildParent 的子类,因此底层 Parent 对象必须在 Child 对象之前创建。

这与实例变量有什么关系?嗯,它们仅在创建对象时才存在。因此,在创建 Parent 对象时,Child 的实例变量不可用。在下面的例子中

class OtherChild extends Parent {
    private String prefix = "some ";
    public OtherChild(String s) {
        // don't try to put an instruction here, it's impossible due to the mandatory call to super as first instruction
        super(prefix+s);
        System.out.println("child created with "+s);
    }
}

您将遇到初始化错误,因为调用 super 构造函数时 prefix 字段未初始化,因为此时 Child 对象实际上还不存在。我的解释够清楚吗?

关于java - 不允许在调用 super 构造函数时使用实例变量和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4872998/

相关文章:

java - Recyclerview 构造函数不保存参数

java - 带有通配符的列表会导致通用巫毒教错误

java - 如何在 MVC Java 中实现我的代码?

java - Math.pow(a,n) JAVA的时间复杂度

java - 在 Java 中反转嵌套的 TreeMap

java - 如何访问Cassandra节点本地数据

c# - 调用 COM 类的非默认构造函数

c++:没有重载函数的实例?

exception - 构造函数什么时候抛出异常是正确的?

java - 具有初始值的链表构造函数