Class initialization, constructor, static member variables, loading order of static blocks in java

1. The concept of compilation and operation should be clarified: compilation is the process of javac, which is responsible for compiling .java files into .class files, mainly type, format checking and compiling into bytecode files, and loading refers to the process of java *, Load the .class file into memory to interpret and execute, that is, it will only be loaded when it is running.

2. The loading time of the class is definitely at runtime, but it is not loaded all at once, but dynamically on demand, relying on reflection to achieve dynamic loading. Generally speaking, a class will only be loaded once, and then it will be loaded from the jvm It can be obtained from the cache of the class instance of the .

Although the Java virtual machine specification does not have a mandatory constraint on when to start the class loading process, for the initialization of the class, the virtual machine specification strictly stipulates that there are only four situations in which the class must be initialized immediately. When encountering new, getStatic, and putStatic Or when the four bytecode instructions of invokeStatic are used, if the class has not been initialized, its initialization needs to be triggered first. 
The most common java code scenario to generate these 4 instructions is:

1) Instantiate an object using the new keyword

2) Read a static field of a class (except for static fields modified by final and the result has been placed in the constant pool at compile time)

3) Set a static field of a class (except for static fields that are modified by final and that have placed the result in the constant pool at compile time)

4) Call a static method of a class

Simply put, when a class is used for the first time.

Execution order to initialize a class:

If the class has not been loaded: 
1. Execute the static code block and static variable initialization of the parent class first, and the execution order of the static code block and static variables is only related to the order in which they appear in the code. 
2. Execute the static code block and static variable initialization of the subclass. 
3. Execute the instance variable initialization of the parent class (for example: int a; initialization is 0, and the reference type is null) 
4. Execute the constructor of the parent class 
5. Execute the instance variable initialization of the subclass (for example: int a; initialization is 0 , the reference type is null) 
6. Execute the constructor of the subclass 
If the class has been loaded: 
the static code block and static variables do not need to be executed repeatedly, and when the class object is created, only the variable initialization and construction methods related to the instance are executed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324849192&siteId=291194637