[英]Why does my child class not initialize variables properly in java
In the code below, myString is always initialized to null.在下面的代码中,myString 始终初始化为 null。 I have to manually initialize in an init() or similar.我必须手动初始化 init() 或类似的。 As far as I can tell it is related to superclass/subclass but I don't understand the exact mechanism据我所知,它与超类/子类有关,但我不了解确切的机制
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() {
}
}
The issue with your code is, that myString
is initialized at the begin of the constructor of class A
but right after the super constructor (ie class B
).您的代码的问题是, myString
是在 class A
的构造函数开始时初始化的,但在超级构造函数之后(即 class B
)。 Since you access the variable before from the constructor of class B
(indirectly via call to overriden methode c
) your get this behaviour.由于您之前从 class B
的构造函数访问变量(间接通过调用覆盖的方法c
)您会得到这种行为。
As a rule of thumb: if you want to avoid unexpected behavior do not call overriden methods before the constructor has been executed.根据经验:如果您想避免意外行为,请不要在构造函数执行之前调用覆盖的方法。
Add a call to c();
添加对c();
overidden method right after the object has been fully created and call to superclass constructor is done.在完全创建 object 并完成对超类构造函数的调用之后的重写方法。
Change your code to this..将您的代码更改为此..
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
Thinking in Java Second Edition by Bruce Eckel, Behavior of polymorphic methods inside constructors (p. 337-339).在 Bruce Eckel 的 Java 第二版中的思考,构造函数内的多态方法的行为(第 337-339 页)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.