构造函数调用中的意外输出
class SuperclassA {
protected int superValue; // (1)
SuperclassA() { // (2)
System.out.println("Constructor in SuperclassA");
this.doValue(); // (3)
}
void doValue() { // (4)
this.superValue = 911;
System.out.println("superValue: " + this.superValue);
}
}
class SubclassB extends SuperclassA {
private int value = 800; // (5)
SubclassB() { // (6)
System.out.println("Constructor in SubclassB");
this.doValue();
System.out.println("superValue: " + this.superValue);
}
void doValue() { // (7)
System.out.println("value: " + this.value);
}
}
public class Javaapp {
public static void main(String[] args) {
System.out.println("Creating an object of SubclassB.");
new SubclassB(); // (8)
}
}
为什么我的输出是:
Creating an object of SubclassB.
Constructor in SuperclassA
value: 0
Constructor in SubclassB
value: 800
superValue: 0
我想这应该是这样的:
Creating an object of SubclassB.
Constructor in SuperclassA
value: 800
Constructor in SubclassB
value: 800
superValue: 0
class SuperclassA {
protected int superValue; // (1)
SuperclassA() { // (2)
System.out.println("Constructor in SuperclassA");
this.doValue(); // (3)
}
void doValue() { // (4)
this.superValue = 911;
System.out.println("superValue: " + this.superValue);
}
}
class SubclassB extends SuperclassA {
private int value = 800; // (5)
SubclassB() { // (6)
System.out.println("Constructor in SubclassB");
this.doValue();
System.out.println("superValue: " + this.superValue);
}
void doValue() { // (7)
System.out.println("value: " + this.value);
}
}
public class Javaapp {
public static void main(String[] args) {
System.out.println("Creating an object of SubclassB.");
new SubclassB(); // (8)
}
}
why is my output:
Creating an object of SubclassB.
Constructor in SuperclassA
value: 0
Constructor in SubclassB
value: 800
superValue: 0
i suppose this should be like:
Creating an object of SubclassB.
Constructor in SuperclassA
value: 800
Constructor in SubclassB
value: 800
superValue: 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在第一个
value
输出中看到0
的原因是,value
的字段初始值设定项(将其设置为 800)将不会运行,直到就在SubclassB
的构造函数即将被调用之前。在构造SuperclassA
期间(必须在构造子类之前发生),value
在其未初始化状态下被观察到,即 0。The reason you see
0
for the firstvalue
output is that the field initializer forvalue
(which sets it to 800) will not be run until just before the constructor forSubclassB
is about to be called. During the construction ofSuperclassA
(which must occur prior to the construction of the subclass,)value
is observed in its unitialized state, which is 0.SuperclassA
的this.doValue()
正在调用SubClassB
和value 中的
不会被初始化。有关详细信息,请参阅 http://en.wikipedia.org/wiki/Method_overriding。doValue()
方法在创建SubClassB
之前,SuperclassA
'sthis.doValue()
is calling thedoValue()
method inSubClassB
andvalue
does not get initialized untilSubClassB
is being created. See http://en.wikipedia.org/wiki/Method_overriding for more information.