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


当前回答

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

其他回答

私有构造函数防止调用者显式实例化类 请参阅PrivateConstructor的进一步信息

我以为有人会提到这一点(第二点),但是…私有构造函数有三种用法:

to prevent instantiation outside of the object, in the following cases: singleton factory method static-methods-only (utility) class constants-only class . to prevent sublcassing (extending). If you make only a private constructor, no class can extend your class, because it can't call the super() constructor. This is some kind of a synonym for final overloaded constructors - as a result of overloading methods and constructors, some may be private and some public. Especially in case when there is a non-public class that you use in your constructors, you may create a public constructor that creates an instance of that class and then passes it to a private constructor.

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

Yes.

这样您就可以控制类的实例化方式。如果将构造函数设为私有,然后创建一个返回类实例的可见构造函数方法,则可以限制创建的数量(通常是保证只有一个实例)或回收实例或其他与构造相关的任务。

执行new x()从不返回null,但是使用工厂模式,您可以返回null,甚至返回不同的子类型。

也可以将它用于没有实例成员或属性,只有静态成员或属性的类——就像在实用函数类中一样。

是的,构造函数可以是私有的。私有构造函数阻止任何其他类实例化私有构造函数的示例

public class CustomHttpClient {
private static HttpClient customHttpClient;

/** A private Constructor prevents any other class from instantiating. */
private CustomHttpClient() {
}}