私有构造函数是默认构造函数,它的用途是什么?

时间:2014-06-10 09:28:50

标签: java

如果我在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 个答案:

答案 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();

可通过默认构造函数语法实现。