package code.classloader; public class Interesting { public static int count1; public static int count2 = 0; public static Interesting ins = new Interesting(); private Interesting() { count1++; count2++; } public static Interesting getInstance() { return ins; } public static void main(String[] args) { Interesting ins = Interesting.getInstance(); System.out.println(ins.count1); System.out.println(ins.count2); } }
看看這段代碼,想一下輸出結果。。。count1=? count2=?
然后再看另外一段
package code.classloader; public class Interesting { public static Interesting ins = new Interesting(); public static int count1; public static int count2 = 0; private Interesting() { count1++; count2++; } public static Interesting getInstance() { return ins; } public static void main(String[] args) { Interesting ins = Interesting.getInstance(); System.out.println(ins.count1); System.out.println(ins.count2); } }
有沒有看到區別啊??看不出來的先去掛個眼科哈!!!想想這段代碼的輸出結果 count1 和count2的值
這個問題號稱全世界百分之九十的java程序員第一次看到都會犯的錯,是不是很牛逼的樣子。。
這段代碼雖然很簡單,但卻是涵蓋了類加載的一系列過程。
答案下回詳細分解。。😁