我在代码的注释中添加了我的问题。
class Parent{
int num =9; //I think num in Parent class is overrided by the num in Child class. why is the num in the first line of output is still 9?
{ //code block
System.out.println("Parent constructor code..."+num);
}
Parent(){
System.out.println("Parent constructor run");
show(); //why does this method here invoke the show() method in Child class?
}
void show() {
System.out.println("Parent show..."+num);
}
}
class Child extends Parent{
int num = 8;
{
System.out.println("Child constructor code..."+num);
num = 10;
}
Child(){
System.out.println("Child constructor run");
show();
}
void show() {
System.out.println("Child show..."+num);
}
}
public class Test {
public static void main(String[] args) {
new Child();
}
}
输出是:
父构造函数代码...9
父构造函数运行
子显示...0
子构造函数代码...8
子构造函数运行
子显示...10
感谢你们!我发现这是一个可变的阴影和隐藏问题。
侃侃无极
小怪兽爱吃肉
慕莱坞森
相关分类