构造函数可以是私有的吗?私有构造函数如何有用?


当前回答

是的,构造函数可以是私有的。这个有不同的用法。其中一种用途是用于单例设计反模式,我建议您不要使用这种反模式。另一个更合理的用途是委托构造函数;你可以有一个构造函数它有很多不同的选项这是一个实现细节,所以你把它设为私有,但是你剩下的构造函数都委托给它。

作为委托构造函数的一个例子,下面的类允许您保存一个值和一个类型,但它只允许您为类型的子集这样做,因此需要将通用构造函数设置为私有,以确保只使用允许的类型。公共私有构造函数有助于代码重用。

public class MyClass {
     private final String value;
     private final String type;

     public MyClass(int x){
         this(Integer.toString(x), "int");
     }

     public MyClass(boolean x){
         this(Boolean.toString(x), "boolean");
     }

     public String toString(){
         return value;
     }

     public String getType(){
         return type;
     }

     private MyClass(String value, String type){
         this.value = value;
         this.type = type;
     }
}

编辑 几年后再看这个答案,我想指出,这个答案既不完整,也有点极端。单例的确是一种反模式,通常应该尽可能避免使用;然而,除了单例外,私有构造函数还有很多用途,我的回答只提到了一种。

再举几个使用私有构造函数的例子:

To create an uninstantiable class that is just a collection of related static functions (this is basically a singleton, but if it is stateless and the static functions operate strictly on the parameters rather than on class state, this is not as unreasonable an approach as my earlier self would seem to suggest, though using an interface that is dependency injected often makes it easier to maintain the API when the implementation requires larger numbers of dependencies or other forms of context). When there are multiple different ways to create the object, a private constructor may make it easier to understand the different ways of constructing it (e.g., which is more readable to you new ArrayList(5) or ArrayList.createWithCapacity(5), ArrayList.createWithContents(5), ArrayList.createWithInitialSize(5)). In other words, a private constructor allows you to provide factory function's whose names are more understandable, and then making the constructor private ensures that people use only the more self-evident names. This is also commonly used with the builder pattern. For example: MyClass myVar = MyClass .newBuilder() .setOption1(option1) .setOption2(option2) .build();

其他回答

Yes.

私有构造函数用于防止实例初始化,例如您在java中使用的Math final类。单例也使用私有构造函数

是的,它可以。私有构造函数的存在是为了防止类被实例化,或者因为构造只在内部发生,例如工厂模式。更多信息请参见这里。

是的。类可以有私有构造函数。即使是抽象类也可以有私有构造函数。

通过将构造函数设为私有,可以防止类被实例化以及类的子类化。

下面是私有构造函数的一些用法:

单例设计模式 限制创建实例的数量 使用静态工厂方法为对象创建提供有意义的名称 静态实用类或常量类 防止子类化 构建器设计模式,从而创建不可变类

如果一个类中的所有方法都是静态的,那么私有构造函数是个好主意。

是的,类可以有一个私有构造函数。需要禁止从其他类访问构造函数,并在定义的类中保持它的可访问性。

为什么要只在内部创建类的对象?出于任何原因都可以这样做,但一个可能的原因是您想实现单例对象。单例是一种设计模式,它只允许创建类的一个实例,这可以通过使用私有构造函数来实现。