PackageInit;classPerson {private static person person = new person (); public static int count2 = 5; Public Static intCount1; PrivatePerson () {count1++; Count2++; } Public StaticPerson getinstance () {returnPerson ; }} Public classTestsingleton { Public Static voidMain (string[] args) {System.out.println ("Count1:" +person.count1); System.out.println ("Count2:" +Person.count2); }}
Output:
Count1:1
Count2:5
Reason:
ClassLoader
The class performs three steps before executing:
1. Class loading: Find and load the class's binary data, load the corresponding class file into memory
2. Connect
2.1. Verify: Ensure that the class being loaded is correct (primarily to prevent the disgusting class file from being loaded)
2.2. Prepare: Allocate memory for static variables of the class and initialize them to default values
2.3. Parsing: Converting a conforming reference in a class to a direct reference
3. Initialize: Assigns the correct initial value to the static variable of the class
found that steps 2.2 and 3 refer to the keyword static variables, focusing on these two steps, and 2.2 result will result in a static variable
Person,count1,count2 allocating memory and assigning values (default value)
Person=null;
Count1=count2=0
At step 3, the initialization will give the correct value to the static variable, then when will it be initialized?
all Java Virtual machine implementations must be initialized when each class or interface is "first actively used" by a Java program
Java's use of classes is divided into: active use, passive use
Active use of six kinds: (except for these 6 kinds, the other is passive use)
1. Create an instance of the class
2. Access static variables for a class or interface or assign a value to the static variable
3. Static method of calling class
4. Reflection
5. Subclass of Initialization class
6. Class for startup class when Java Virtual machine is started
That is , when the main method is executed, the static variable is assigned a value, if there are more than one static variable, in the top-down order (the compiler will optimize, and the order of code writing will not be inconsistent)
Count1=1;count2=1 after initialization of the person variable;
public static int count2 = 5; after execution, count2=5
Verify:
PackageInit;classPerson {public static int count2 = 5; private static person person = new person (); Public Static intCount1; PrivatePerson () {count1++; Count2++; } Public StaticPerson getinstance () {returnPerson ; }} Public classTestsingleton { Public Static voidMain (string[] args) {System.out.println ("Count1:" +person.count1); System.out.println ("Count2:" +Person.count2); }}
Output:
Count1:1
Count2:6
http://longpo.iteye.com/blog/2217113
Java ClassLoader Static