Java: calling a superclass constructor that calls an overridden method that sets the subclass field

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!

+7
source share
3 answers
 class Test2 { public int number = 0; } 

equivalently

 class Test2 { public int number; public Test2() { super(); number = 0; } } 

Thus, when the superstructor is called, the number field is set to 1. After returning from the super-constructor, the number task runs at 0.

Just delete the assignment and it should behave as you expect.

+17
source

Your code breaks the golden rule in Java - never call a method in a constructor that can be overridden by a subclass - that is, such methods must be private.

By the time the default constructor finishes in Test2, it overwrites the initial value 1 assigned to it through the initializer public int number = 0; .

+1
source

If they say that Animal extends Dog, and you call Animal a = new Dog ()

Then the sequence of steps will be lower

  • Static animal fields are initialized

  • Running a static block of the animal

  • Dog static fields are initialized <They will be reinitialized if Animal changed them anyway>

  • Static Dog Block Running

  • The non-static field of the animal has been initialized. They will be reinitialized if Animal has changed them anyway>

  • Animal constructor is running

  • Non-static dog field initialized <They will be reinitialized if the Animal changes them>

  • Dog constructor runs

0
source

All Articles