是的,我们可以将构造函数声明为private。如果将构造函数声明为私有,则无法创建类的对象。我们可以在Singleton Design Pattern中使用此私有构造函数 。
私人承建商的条件一个私有的构造不允许一个类被继承。
一个私人constructo[R不允许创建类之外的对象。
如果类中所有常量方法都存在,则可以使用私有构造函数。
如果所有方法都是静态的,那么我们可以使用私有构造函数。
如果我们尝试扩展具有私有构造函数的类,则会发生编译时错误。
示例class SingletonObject {
private SingletonObject() {
System.out.println("In a private constructor");
}
public static SingletonObject getObject() {
// we can call this constructor
if (ref == null)
ref = new SingletonObject();
return ref;
}
private static SingletonObject ref;
}
public class PrivateConstructorDemo {
public static void main(String args[]) {
SingletonObject sObj = SingletonObject.getObject();
}
}
输出结果In a private constructor