构造函数可以是私有的吗?私有构造函数如何有用?
当前回答
Yes.
私有构造函数用于防止实例初始化,例如您在java中使用的Math final类。单例也使用私有构造函数
其他回答
是的。类可以有私有构造函数。即使是抽象类也可以有私有构造函数。
通过将构造函数设为私有,可以防止类被实例化以及类的子类化。
下面是私有构造函数的一些用法:
单例设计模式 限制创建实例的数量 使用静态工厂方法为对象创建提供有意义的名称 静态实用类或常量类 防止子类化 构建器设计模式,从而创建不可变类
我以为有人会提到这一点(第二点),但是…私有构造函数有三种用法:
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.
是的,它用于防止实例化和随后重写。这最常用于单例类中。
是的,它可以。私有构造函数的存在是为了防止类被实例化,或者因为构造只在内部发生,例如工厂模式。更多信息请参见这里。
受到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,并让静态函数返回类实例-请参阅单例模式。但是,非常不鼓励实现单例模式,除非在一些通信只在一个方向上流动的用例中,例如在编写记录器类时
推荐文章
- const构造函数实际上是如何工作的?
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?