gpt4 book ai didi

java - 继承中父字段和子字段如何初始化?

转载 作者:行者123 更新时间:2023-12-02 10:15:06 25 4
gpt4 key购买 nike

我面临着一个困惑。

这是我的小代码片段

public class Father {

public String x;

public Father() {
this.init();
System.out.println(this);
System.out.println(this.x);
}

protected void init() {
x = "Father";
}

@Override
public String toString() {
return "I'm Father";
}

void ParentclassMethod(){

System.out.println("Parent Class");
}

}


public class Son extends Father {
public String x;


@Override
protected void init() {
System.out.println("Init Called");

x = "Son";
}

@Override
public String toString() {
return "I'm Son";
}

@Override
void ParentclassMethod(){
super.ParentclassMethod();
System.out.println("Child Class");
}

}

public class MainCLass{

public static void main(String[] args){

Son ob = new Son();

}

所以当我创建一个从父类继承的儿子的类实例时,JVM会自动调用父亲的类构造函数。当调用父亲的构造函数时,它会创建儿子类型实例,否则父亲的字段将不会初始化。到目前为止很好..!

正如你所看到的,字段x是从Father的类派生到Son的类中的。我的代码使用 init() 方法初始化 x

那为什么它显示为空。

这非常令人困惑。谁能解释一下吗?

最佳答案

Java 中的变量不是多态的。自从您重新声明 x里面Son ,这个变量实际上是一个不同 xFather 中的那个。所以在 init方法Son ,您正在初始化 Sonx ,但不是Fatherx

另一方面,你的陈述System.out.println(this.x);位于 Father 内类,因此它只知道 Fatherx 。由于您不再初始化此变量,因为覆盖 init方法,xFather仍然null (默认),因此它将打印 null .

您可以通过删除 public String x; 来解决该问题来自Son类(class)。这将使 Fatherx唯一x ,解决问题。

但是,一般来说,您希望将此变量设为 private而不是public 。您也不应该调用非 final构造函数中的方法。 It can only introduce bugs 。在这种情况下初始化它的正确方法是使用 Father 中带有参数的构造函数。 :

public class Father {
private String x;

protected Father(String x) {
this.x = x;
System.out.println(this);
System.out.println(this.x);
}

public Father() {
this("Father");
}

// Rest of father's code, without the init method
}

public class Son extends Father {
public Son() {
super("Son");
}

// Rest of son's code, without the init method
}

关于java - 继承中父字段和子字段如何初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54743800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com