2014-06-10 64 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

相关问题