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


当前回答

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

其他回答

如果一个类中的所有方法都是静态的,那么私有构造函数是个好主意。

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

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

私有构造函数防止调用者显式实例化类 请参阅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.