Home >Java >javaTutorial >What's the Actual Order of Field Initialization and Constructor Execution in Java?
Field Initialization in Java Constructors
In Java, the execution order of field initialization and constructor code has been a topic of confusion. The provided code demonstrates this behavior:
class X { Y b = new Y(); X() { System.out.print("X"); } } class Y { Y() { System.out.print("Y"); } } public class Z extends X { Y y = new Y(); Z() { System.out.print("Z"); } public static void main(String[] args) { new Z(); } }
One might expect the output to be "XZYY" based on the assumption that constructors are initialized before instance variables. However, the actual output is "YYXZ":
This output contradicts the expected order because field initialization (e.g., 'b' and 'y') occurs before the execution of constructor bodies (e.g., 'X()' and 'Z()').
The Java Virtual Machine Specification (JVM Spec) clarifies the order of initialization as follows:
Therefore, in the provided code, the instance variables 'b' and 'y' are initialized before the constructor bodies of 'X' and 'Z' are executed, resulting in the output "YYXZ".
The above is the detailed content of What's the Actual Order of Field Initialization and Constructor Execution in Java?. For more information, please follow other related articles on the PHP Chinese website!