Class loading
Before talking about class initialization, let’s explain the loading order of class.
The following is excerpted from "Thinking in Java 4"
Since everything in Java is an object, many activities
This problem is one of the simpler examples. As will be mentioned in the next chapter, the code for each object exists in a separate file. Unless code is really needed, that file will not be loaded. Generally, we can think that the code will not actually load unless an object of that class is constructed. Because there are some subtle ambiguity in the static method, it can also be considered that "class code is loaded when used for the first time".
The first time you use it is also where static initialization occurs. When loading, all static objects and static code blocks are initialized in their original order (that is, the order in which they are written in the class definition code). Of course, the static data will only be initialized once.
To put it simply, when the class has an inheritance relationship, the class loader will shape it backwards and load related classes.
for example:
Class B extends Class A When we new B(), the class loader automatically loads A's code
Initialization order of class
Usually the initialization sequence is as follows:
(static object and static code block, initialized in their order)>Member variables>Constructor
Test code
public class ClassInit { /** * @Title: main * @Description: Class initialization order test* @param: @param args * @return: void * @throws */ public static void main(String[] args) { // TODO Auto-generated method stub new B(); }}class A { static{ System.out.println("A's static code block..."); } public String s1 = prtString("A's member variable..."); public static String s2 = prtString("A's static variable..."); public A(){ System.out.println("A's constructor..."); } public static String prtString(String str) { System.out.println(str); return null; }}class B extends A{ public String ss1 = prtString("B's member variable..."); public static String ss2 = prtString("B's static variable..."); public B(){ System.out.println("B's constructor..."); } private static A a = new A(); static{ System.out.println("B's static code block..."); } { System.out.println("Code block..."); } } Test results
A's static code block...
A's static variable...
B's static variable...
Member variables of A...
A's constructor...
B's static code block...
Member variables of A...
A's constructor...
Member variables of B...
Code block...
The constructor of B...
Summarize
The above is the entire content of the initialization order of class in Java. I hope it will be helpful to everyone using Java.