为什么我的子类没有在 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() {
}
}
In the code below, myString is always initialized to null. I have to manually initialize in an init() or similar. 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() {
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码的问题是,
myString
在类A
的构造函数的开头初始化,但在超级构造函数之后(即类B
)。由于您之前从类B
的构造函数访问变量(通过调用重写方法c
间接),因此您会得到此行为。根据经验:如果您想避免意外行为,请不要在执行构造函数之前调用重写方法。
The issue with your code is, that
myString
is initialized at the begin of the constructor of classA
but right after the super constructor (i.e. classB
). Since you access the variable before from the constructor of classB
(indirectly via call to overriden methodec
) your get this behaviour.As a rule of thumb: if you want to avoid unexpected behavior do not call overriden methods before the constructor has been executed.
在完全创建对象并完成对超类构造函数的调用后,立即添加对
c();
覆盖方法的调用。将您的代码更改为此..
Add a call to
c();
overidden method right after the object has been fully created and call to superclass constructor is done.Change your code to this ..
《Thinking in Java Second Edition》作者:Bruce Eckel,多态方法的行为
构造函数内部(第 337-339 页)。
Thinking in Java Second Edition by Bruce Eckel, Behavior of polymorphic methods
inside constructors (p. 337-339).