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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
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!