package basic.program.test;
class Single {
private static Single obj = new Single(); //优先下面2个字段存在
public static int counter1;
public static int counter2 = 0;
private Single() {
counter1++;
counter2++;
}
public static Single getInstance() {
return obj;
}
}
//测试类
public class TestAdd {
public static void main(String[] args) {
Single obj = Single.getInstance();
System.out.println("obj.counter1==" + obj.counter1);
System.out.println("obj.counter2==" + obj.counter2);
}
}
运行结果:
obj.counter1==1
obj.counter2==0