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


当前回答

是的,它用于防止实例化和随后重写。这最常用于单例类中。

其他回答

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

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.