为什么实例变量和方法不允许调用 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将显示出来。这很正常,因为 Child
是 Parent
的子类,因此底层 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/