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


当前回答

私有构造函数背后的基本思想是限制JVM从外部实例化类,但是如果一个类有参数构造函数,那么它就会推断该类是有意实例化的。

其他回答

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

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

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

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

由于以下原因,可以在Java中定义私有构造函数

为了控制Java对象的实例化,它不允许您创建对象的实例。 它不允许类被子类化 在实现单例模式时,这有一个特殊的优势,它使用私有构造函数,并控制为整个应用程序创建实例。 当你想要一个定义了所有常量的类,并且不再需要它的实例时,我们将这个类声明为私有构造函数。

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

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

Yes.

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

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

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

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

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.