构造函数可以是私有的吗?私有构造函数如何有用?
当前回答
私有构造函数防止调用者显式实例化类 请参阅PrivateConstructor的进一步信息
其他回答
是的。类可以有私有构造函数。即使是抽象类也可以有私有构造函数。
通过将构造函数设为私有,可以防止类被实例化以及类的子类化。
下面是私有构造函数的一些用法:
单例设计模式 限制创建实例的数量 使用静态工厂方法为对象创建提供有意义的名称 静态实用类或常量类 防止子类化 构建器设计模式,从而创建不可变类
Yes.
这样您就可以控制类的实例化方式。如果将构造函数设为私有,然后创建一个返回类实例的可见构造函数方法,则可以限制创建的数量(通常是保证只有一个实例)或回收实例或其他与构造相关的任务。
执行new x()从不返回null,但是使用工厂模式,您可以返回null,甚至返回不同的子类型。
也可以将它用于没有实例成员或属性,只有静态成员或属性的类——就像在实用函数类中一样。
Yes.
私有构造函数用于防止实例初始化,例如您在java中使用的Math final类。单例也使用私有构造函数
受到Robert C. Martin的“Clean Code”的启发,我整理了一个例子:
/**
When overloading constructors, it is best practise to only allow the use of
different constructors than the standart one by explicitly enforcing the
useage of a static function to highlight the use of the overloaded constructor
in example:
Animal a = Animal.CreateInsectOrArachnia(2, "black", 8); //hatch a black widow
*/
class Animal
{
private int size;
private String color;
private int legs;
public Animal(int size, String color)
{
this.size = size;
this.color = color;
this.legs = 4;
}
//will prevent the instanciation of Animal with this constructor
private Animal(int size, String color, int legs)
{
this.size = size;
this.color = color;
this.legs = legs;
}
public static Animal CreateInsectOrArachnia(int size, String color, int legs)
{
return new Animal (size, color, legs);
}
}
Martins明确指出,应该阻止用户访问“标准构造函数”以外的构造函数,并应该强制使用静态初始化函数,以强调“你所做的可能没有错,但它与该类的预期使用不同”。
[他没有使用这个确切的措辞,我试图把它挤进这个定义-对不起,罗伯特:^)]
作为旁注,完全可以将类中唯一的构造函数(即标准构造函数)完全声明为private,并让静态函数返回类实例-请参阅单例模式。但是,非常不鼓励实现单例模式,除非在一些通信只在一个方向上流动的用例中,例如在编写记录器类时
私有构造函数背后的基本思想是限制JVM从外部实例化类,但是如果一个类有参数构造函数,那么它就会推断该类是有意实例化的。
推荐文章
- 在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__之外