Java – why is my field not initialized to the value I gave it
•
Java
I have the following courses:
public abstract class AClass { public AClass() { aMethod(); } abstract protected void aMethod(); } public class SubClass extends AClass { private int x = 5; private static final int y = 6; @Override protected void aMethod() { System.out.println("x: " + x + " | y: " + y); } } public class Main { public static void main(String[] args) { new SubClass(); } }
Running main prints the following: X: 0 | Y: 6
Why does 0 print x?
Solution
The cause of the bad behavior is the wrong initialization sequence:
>New subclass() executes aclass constructor > aclass constructor calls amethod() > amethod() shows x (0 so far), y is 6 because it is static) > subclass initializes its non static field, so x becomes 5
To avoid confound, do not call virtual methods (especially overriden) in constructors.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码