To further understand the class initialization process, it is necessary to further differentiate the class instantiation (class instance) and Class Object Instantiation (object instance). What we call instantiation usually refers to Object Instantiation.
We can simply divide the use of classes into three processes: class loading, class instantiation, and Object Instantiation.
Class loading: the class to be used by the Java Virtual Machine is loaded into the memory according to requirements, so that the classCodeThe Code is available. For interpreted virtual machines, this code can be directly interpreted and executed. For JIT technology, generally, virtual machines compile bytecode into the target machine language when the method is called for 1st times, and how much is required. Class is loaded inProgramGenerally, it is executed only once during running.
Class instantiation: in fact, instantiation mainly allocates space for member variables. Of course, the Code itself does not matter and is public. Class instantiation is mainly because the class can have static variables. It is necessary to allocate space for these static members of the class and perform initialization of these static member variables; class instantiation is only executed once during a program running. You must note that class loading can be performed locally or remotely, because the class code is essentially some data (Character Sequence ).
Object Instantiation: A class is a static description of objects with common features and behaviors (a data type ), object Instantiation is to use classes as a model to allocate specific memory space for each object to form an independent entity. Of course, the allocation space here is mainly for member variables, and the member methods are all code, it is shared by all objects, so you do not need to allocate space to save a copy of the code.
In the previous process above, all subsequent processes must have been executed.
For Class A, if Class A is not loaded, the call of Class A will cause class loading, but will not cause class instantiation. The call of class. forname ("A") will not only execute class loading, but also execute class instantiation. In fact, this method also has an overload method, which can indicate whether class instantiation is performed, and can also specify whether to load locally or remotely (using classloader ).