下面的代码counter1,counter2输出的结果是什么,把第10行放到12行后面,ounter1,counter2输出的结果是什么? 为什么?
1 public class Test { 2 public static void main(String[] args) { 3 System.out.println(Singleton.counter1); 4 System.out.println(Singleton.counter2); 5 } 6 7 } 8 9 class Singleton{ 10 private static Singleton singleton = new Singleton(); 11 public static int counter1; 12 public static int counter2=0; 13 private Singleton(){ 14 counter1++; 15 counter2++; 16 } 17 public static Singleton getInstance(){ 18 return singleton; 19 } 20 }
1. counter1=1,counter2=0
原因是类初始化的准备阶段,会为静态变量分配内存,并设置默认初始值,此时singleton=null,counter1=0,counter2=0;然后在初始化阶段,为静态变量赋初始值,这时从上往下初始化,先new Singleton(), counter1=1,counter2=1,然后11行counter1没变,counter2被重新赋值为0。
2. counter1=1,counter2=1
原因是代码顺序换了,new Singleton()在后面执行。