I have add my question in the comment of the code.
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();
}
}
the output is:
Parent constructor code...9
Parent constructor run
Child show...0
Child constructor code...8
Child constructor run
Child show...10
thank you guys! I have figured out that it's a variable shadowing and hiding problem.