构造函数可以是私有的吗?私有构造函数如何有用?
当前回答
是的,它可以。私有构造函数的存在是为了防止类被实例化,或者因为构造只在内部发生,例如工厂模式。更多信息请参见这里。
其他回答
私有构造函数防止调用者显式实例化类 请参阅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() {
}}
推荐文章
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 应该……接住环内还是环外?
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 实例属性attribute_name定义在__init__之外