为什么我的子类无法在Java中正确初始化变量

问题描述

| 在下面的代码中,myString始终初始化为null。我必须手动初始化init()或类似的东西。据我所知,它与超类/子类有关,但我不了解确切的机制
public class A extends B {

    private String myString = \"test\";


    public static void main(String[] args) {
        new A();
    }

    public A() {
        super();

    }

    public void c() {
        System.out.println(myString);
    }

}

public class B {

    public B() {
        c();
    }

    public void c() {

    }
}
    

解决方法

        您的代码的问题在于,在类
A
的构造函数的开头但在超级构造函数(即类
B
)之后立即初始化了
myString
。由于您之前是从类
B
的构造函数访问变量的(通过对覆盖的方法
c
的调用间接访问),因此可以得到此行为。 根据经验,如果要避免意外行为,请不要在执行构造函数之前调用重写的方法。     ,        在完全创建对象并完成对超类构造函数的调用之后,立即添加对
c();
重写方法的调用。 将您的代码更改为此。
public class A extends B {

    private String myString = \"test\";


    public static void main(String[] args) {
        new A();
    }

    public A() {
        super();
         c();     // Include the call to c(); here ...

    }

    public void c() {
        System.out.println(myString);
    }

}

public class B {

    public B() {

    }

    public void c() {

    }
} 

 // Output : test
    ,        Bruce Eckel在Java第二版中的思考,多态方法的行为 内部构造函数(第337-339页)。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...