Class加载的一个有趣的例子
2018-09-22 本文已影响56人
小超人爱小土豆
看一下下面两个程序的执行结果
class Singleton {
private static Singleton singleton = new Singleton();
public static int count1 =;
public static int count2 = 0;
public static Singleton getInstance() {
return singleton;
}
private Singleton() {
++count1;
count2++;
}
}
public class Test1 {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
System.out.println("1 " + singleton.count1);
System.out.println("2 " + singleton.count2);
}
}
------------------------------------------------------------------------------------
class Singleton {
public static int count1 =;
public static int count2 = 0;
private static Singleton singleton = new Singleton();
public static Singleton getInstance() {
return singleton;
}
private Singleton() {
++count1;
count2++;
}
}
public class Test1 {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
System.out.println("1 " + singleton.count1);
System.out.println("2 " + singleton.count2);
}
}
最后的结果是多少?
答案:
1 1
2 0
1 1
2 1