Supplement: Under what circumstances will classes in Java be loaded and initialized

Will be loaded and initialized:

1. When the virtual machine starts, it will first initialize the class where the main method is located;

2. New an object of a class, when creating an instance of the class;

3. Use reflection to force the creation of a java.lang.Class object corresponding to a certain class or interface;

4. Initialize the subclass of a certain class, the parent class of the subclass will be initialized first;

5. Call a class method (static method) of a certain class;? ? ?

6. Access a certain class variable or assign a value to the variable.

7. Run a main class directly using java.exe command, the main class is initialized first. 

Note: Static modified properties and methods are initialized when the class is loaded, and ordinary properties and methods are initialized when the class instance object is created.

 
The case of not being initialized: 

1. The static field of the parent class is referenced by the subclass, and the subclass will not be initialized. ?

2. Call the constants of the class; that is, access the constants (the constants are put into the constant pool in the link phase);

3. Defining class references through an array will not cause the initialization of the class;

TestClass[] testClassArr = new TestClass[5]; \\ will not cause the TestClass class to be initialized


Note:

          (1) This blog is reproduced from: https://blog.csdn.net/guoqingshuang/article/details/87970688 ; https://www.cnblogs.com/ryokai/p/13607643.html ; https://www .cnblogs.com/codezpc/p/12703440.html (the last entry of this blog is doubtful);

          (2) The content of class loading, connection, and initialization is not fully understood by myself at present, so I will leave it to the subsequent deepening! ! !

Guess you like

Origin blog.csdn.net/csucsgoat/article/details/114815885