class insect{private int i = 9; protected static int J; Insect () {print.print ("i =" + i + ", j =" + j); j = 39; } private static int x1 = Printinit ("Static insect.x1 initialization"); static int Printinit (String s) {print.print (s); Return 47; }}public class Beetle extends insect{private int k = Printinit ("BEETLE.K initialization"); Public Beetle () {print.print ("k =" + K); Print.print ("j =" + j); } private static int x2 = Printinit ("Static beetle.x2 initialization"); public static void Main (string[] args) {print.print ("Beetle constructor"); Beetle a= new Beetle (); }}/* output static insect.x1 initialization
Static BEETLE.X2 initialization
Beetle constructor
i = 9,j = 0
beetle.k initialization
K = +-
J =
i = 9,j = *///:~
The first thing that happens when you run Java on Beetle is to try to access Beetle.main (), and in the process of loading it, the compiler discovers that it has a base class, the base class is first loaded, and then static initialization in the base class is executed. So the first statement in output is static insect.x1 initialization, and the following Beetle class begins to perform the same steps as the base class, so the static beetle.x2 initialization gets output. So far, the necessary classes have been loaded and the objects can be created. When you create object A, the constructor is called, and the code in the constructor and the static code snippet executes sequentially, so the output i = 9,j = 0
When the load is complete, the main function is executed and the first executed statement is Print.print ("Beetle constructor"), so Beetle constructor is generated in output.
Before the constructor of the base class is called, all the base types in the object are set to the default values, and the object references are set to null-. This is generated by setting the object memory to a binary 0 value. The constructor for the base class is then called. In this case, it is called automatically, and the base class constructor and the constructor of the exported class go through the same procedure in the same order. After the base class constructor is complete, the instance variables are initialized in their order. So there is k = 47,j = 39 output.
Recognize the initialization and inheritance of constructors in Java again