Home >Java >javaTutorial >Why Does This Java Program Output 'YYXZ' Instead of 'XZYY'?
Understanding Initialization Order in Java Constructors
When constructing an object in Java, it's crucial to comprehend the order of initialization. This question arises: "Can anyone clarify the output of the following program?"
The code:
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(); } }
The expected output was "XZYY" under the assumption that constructors are initialized before instance variables. However, the output is actually "YYXZ." This deviation highlights the importance of understanding the actual initialization order.
According to the Java Virtual Machine Specification, the initialization order is as follows:
In this case, the static variables and blocks are not involved. The super() call occurs implicitly in the constructor of class Z, so it is not visible in the code. Therefore, the initialization order is:
This explains the output "YYXZ."
The above is the detailed content of Why Does This Java Program Output 'YYXZ' Instead of 'XZYY'?. For more information, please follow other related articles on the PHP Chinese website!