如果我在java中编写私有构造函数而不是像默认构造函数那样工作?私有构造函数在类中有什么用?
public class BillPughSingleton {
private BillPughSingleton() {
}
private static class LazyHolder {
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance() {
return LazyHolder.INSTANCE;
}
}
还解释了此代码的工作原理以及返回的值
答案 0 :(得分: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();
可通过默认构造函数语法实现。