給大家看段比較有意思的代碼


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程序員第一次看到都會犯的錯,是不是很牛逼的樣子。。

 這段代碼雖然很簡單,但卻是涵蓋了類加載的一系列過程。

 答案下回詳細分解。。😁 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM