I have the following code.
class X { X(){ super(); System.out.println("X()"); } } class Y extends X { Y(){ super(); System.out.println("Y()"); } } class Z extends Y { Z(){ super(); System.out.println("Z()"); } public static void main(String args[]){ Z z1 = new Z(); } }
And I get the conclusion
X() Y() Z()
All perfectly. It is as it should be. And when I make a static object X () in class Z, as follows
class X { X(){ super(); System.out.println("X()"); } } class Y extends X { Y(){ super(); System.out.println("Y()"); } } class Z extends Y { static X x1 = new X(); Z(){ super(); System.out.println("Z()"); } public static void main(String args[]){ Z z1 = new Z(); } } X() X() Y() Z()
The conclusion is over because static instances are first loaded into RAM. But when I make an instance of a static object as follows
X x1 = new X();
I get the following output
X() Y() X() Z()
What really bothers me. As for my knowledge, I should get the following conclusion
X() Y() Z() X()
First, an instance of Z will be created, and X must finally be created. In this case, it is created on the third. Why is this? Is there any special concept that applies here?
source share