【发布时间】:2018-06-19 09:47:08
【问题描述】:
我正在尝试在“Thingking in Java 第 4 版”中进行“重用/E07_SimpleInheritance2”练习。代码有效,但控制台中的输出是:
A: New instance C
B: New instance B
C: New instance C
但我认为C应该在B前面,因为这句话“System.out.println('C:' + str);”是在C2的构造函数中,后面是实例B。嗯,为什么不呢?
好的,我刚刚在初始化时意识到,序列是:(静态变量,静态字段)>(变量,字段)>构造函数。这就是原因。问题解决了,谢谢楼上的大佬 :)
class A2{
A2(String str){
System.out.println("A: " + str);
}
}
class B2{
B2(String str){
System.out.println("B: " + str);
}
}
class C2 extends A2{
C2(String str){
super(str);
System.out.println("C: " + str); //I think it should work first
}
B2 b = new B2("New instance B"); //Then followed by B
}
public class Q7_7_SimpleInheritance2 {
public static void main(String[] args) {
C2 c = new C2("New instance C");
}
}
【问题讨论】:
-
请添加代码以实例化您的对象
-
@DawoodibnKareem 哎呀,我看错了。认为他的问题是为什么“A”出现在“B”之前。
标签: java inheritance constructor