Let's look at an example:
PackageCore.java;classsingleton{Private StaticSingleTon instance =NewSingleTon (); Public Static intNUM1; Public Static intnum2 = 0; PrivateSingleTon () {NUM1++; Num2++; } Public StaticSingleTon getinstance () {returninstance; }} Public classClassloadertest { Public Static voidMain (string[] args) {SingleTon single=singleton.getinstance (); System.out.println ("NUM1:" +single.num1); System.out.println ("NUM1:" +single.num2); }}
What is the output? Maybe a lot of people make mistakes.
Run it for a moment:
This involves the loading and initialization of classes:
1. When the class is invoked actively, the class is loaded, and the JVM finds and loads the class's binary data into memory
2. The JVM checks the class file for correctness, as it prevents the malicious manual generation of class files
3. Allocate memory for static variables of the class and initialize default values.
This step is key, where the initialization default value is not an assignment, such as when the value of instance is Null,num1 is 0,num2 is 0. And at this point the num2 0 is not ' = ' 0 of the assigned value
4. Convert the symbol reference of a class to a direct reference. That is: the reference into a pointer, this is a pointer in Java, Java in the application development process is not a pointer, but there are some in the JVM.
5. Initialization
A) instance = new SingleTon () Call construction method, value of NUM1 and Num2 is assigned to 1
b) NUM1 user does not give default value, maintain 1;
c) num2 user gave the default value of 0, 0 was assigned to NUM2;
(not to be continued)
Update 1:2018-01-01, give an example
Java-core:classloader detailed, Update 1