class Singleton{
public static Singleton t = new Singleton();
public static int count1;
public static int count2 = 0;
private Singleton(){
count1++;
count2++;
}
public static Singleton getInstance(){
return t;
}
}
public class Test6 {
public static void main(String[] args){
Singleton t7 = Singleton.getInstance();
System.out.println(Singleton.count1);
System.out.println(Singleton.count2);
}
}
结果:
1
0
Singleton t7 = Singleton.getInstance():调用类的静态方法,进行类的初始化。在准备阶段,对类变量进行“零值”初始化,t=null、count1=0、count2=0。在初始化阶段,new Singleton()直接调用构造方法,count1=1、count2=1。调用构造方法之后,继续初始化t变量之后的字段。count1=1、count2=0。
System.out.println(Singleton.count1):输出:1
System.out.println(Singleton.count2):输出:0