// 情况一
public class Test1 {
// 3 count1 == 0 count2 == 0
private static Test1 test1 = new Test1();
public static int count1=1;
public static int count2 = 5;
private Test1() {
// 4
count1++;
count2++;
System.out.println("ConstructorInit");
}
{
// 1
System.out.println("init");
}
static {
// 2
System.out.println("initStatic");
}
public static Test1 getInstance() {
return test1;
}
public static void main(String[] args) {
Test1 test1 = Test1.getInstance();
System.out.println(Test1.count1);
System.out.println(Test1.count2);
}
}
//输出
// init
//ConstructorInit
//initStatic
//1
// 5
情况二:
// 情况一
public class Test1 {
// 3 count1 == 0 count2 == 0
public static int count1=1;
public static int count2 = 5;
private static Test1 test1 = new Test1();
private Test1() {
// 4
count1++;
count2++;
System.out.println("ConstructorInit");
}
{
// 1
System.out.println("init");
}
static {
// 2
System.out.println("initStatic");
}
public static Test1 getInstance() {
return test1;
}
public static void main(String[] args) {
Test1 test1 = Test1.getInstance();
System.out.println(Test1.count1);
System.out.println(Test1.count2);
}
}
//输出
// init
//ConstructorInit
//initStatic
//2
// 6
参考: