Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在继承中初始化父字段和子字段?_Java_Inheritance - Fatal编程技术网

Java 如何在继承中初始化父字段和子字段?

Java 如何在继承中初始化父字段和子字段?,java,inheritance,Java,Inheritance,我面临一个困惑 这是我的小代码片段 public class Father { public String x; public Father() { this.init(); System.out.println(this); System.out.println(this.x); } protected void init() { x = "Father"; } @Overr

我面临一个困惑

这是我的小代码片段

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
是从父类派生到子类的。 我的代码使用
init()
方法初始化
x

那为什么它显示为空呢


这很令人困惑。有人能解释吗?

变量在Java中不是多态的。由于您在
Son
中重新声明了
x
,因此该变量实际上与
Father
中的变量不同。因此,在子的
init
方法中,您正在初始化子的
x
,而不是父的
x

另一方面,您的语句
System.out.println(this.x)
在父类中,因此它只知道父类的
x
。由于重写
init
方法而不再初始化此变量,因此
Father
中的
x
将保持
null
(默认值),因此它将打印
null

您可以通过删除
公共字符串xSon
类中选择code>。这将使父亲的
x
成为唯一的
x
,从而消除问题

但是,一般情况下,您希望将此变量设置为
private
,而不是
public
。您也不应该在构造函数中调用非
final
方法。在这种情况下,初始化它的正确方法是在
父类中有一个带参数的构造函数

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
}

不要从构造函数中调用可重写的方法。请尝试从Son类中删除
字符串x
,并在Son的
init()
中调用
super.x=“Son”
,字段不是固有的,只有实例方法