I have this demo code:
class Test2 extends Test { public int number = 0; @Override public void set(){ number = 1; info(); } @Override public void info(){ System.out.println(number); } } public class Test { public Test(){ set(); } public void set(){ } public void info(){ } public static void main(String[] args){ Test2 object = new Test2(); object.info(); } }
The code outputs this result:
1 0
Why? I expect the result:
1 1
In my opionion, the main function calls the constructor of the Test2 class to create the object. The constructor calls the automatic constructor of the superclass. This constructor calls the set () method, which is overridden. Therefore, the set () method of the Test2 class is called. This method sets the field and calls the info () method, which records the number. Then the main function calls the info () method of the created object again.
The number field is set correctly, since the first line output is "1". But why does the second line contain 0? It seems that the field has not been set at all. Can you explain this?
What should I do to get the behavior I expect? Thanks in advance!
user1608790
source share