2014-06-10 133 views
-3

如果我寫在java中的私人構造函數比它的默認構造函數的作品?在課堂上使用私有構造函數是什麼?是一個私有構造函數的默認構造函數,它的用途是什麼?

public class BillPughSingleton { 
private BillPughSingleton() { 
} 

private static class LazyHolder { 
    private static final BillPughSingleton INSTANCE = new BillPughSingleton(); 
} 

public static BillPughSingleton getInstance() { 
    return LazyHolder.INSTANCE; 
} 

}

也解釋這段代碼是如何工作的,什麼是價值迴歸

+1

它只提供BillPughSingleton類的一個實例。這是Singleton設計模式。 – Viraj

回答

3

私有構造不帶參數防止BillPughSingleton從外面BillPughSingleton範圍,例如創建

// Compile time error: BillPughSingleton() is private 
    BillPughSingleton instance = new BillPughSingleton(); 

    // The right and the ONLY way to get (single) instance: 
    BillPughSingleton instance = BillPughSingleton.getInstance(); 

如果沒有構造(包括private BillPughSingleton())聲明,該

// if no constructors are declared, this wrong call becomes possible 
    BillPughSingleton instance = new BillPughSingleton(); 

通過默認構造函數的語法成爲可能。

+0

謝謝德米特里Bychenko :) – user3438822

相關問題