Java中的构造函数可以是私有的吗
Possible Duplicates:
Question about constructors in Java
Can a constructor in Java be private?
Can a constuctor be private in Java? in what kind of situation we use it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的。您可能会使用它来实现工厂模式。
Yes. You would probably use this to implement the factory pattern.
如果将所有构造函数设为私有,则不可能对类进行子类化:
You make it impossible to subclass your class if you make all the constructors private:
是的,在 Java 和其他语言中构造函数可以是私有的。 a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow">单例模式因使用私有构造函数而闻名。
第一篇链接文章中的其他示例:
当您想要控制对象的实例化方式(如果有的话)时,可以使用私有构造函数。例如,在 C# 中,您可以显式定义静态类并强制该类仅包含静态成员和常量。您无法在 Java 中显式执行此操作,但可以使用私有构造函数来防止实例化,然后在类中仅定义静态成员,并且基本上有一个静态类。
常量类就是一个例子,但您也可以在可能包含实用函数(例如基本数学运算)的类中使用它,并且拥有一个实例是没有意义的,因为它只包含常量(例如 pi 和 e) )和静态数学方法。
Yes, constructors can be private in Java and other languages.. The singleton pattern is well known for using a private constructor.
Other examples from the first linked article:
You can make use of a private constructor when you want to control how an object is instantiated, if at all. For example, in C# you can explicitly define a static class and force the class to only contain static members and constants. You can't do this explicitly in Java but you can use a private constructor to prevent instantiation and then define only static members in the class and have basically a static class.
The class for constants is an example of this but you can also use it in a class that might contain utility functions (basic Math operations for example) and it makes no sense to have an instance since it would contain only constants (like pi and e) and static mathematical methods.
构造函数可以是私有的。这最常用于单例模式,或者如果您只想通过静态工厂方法访问对象。
例子
A constructor can be private. This is most often used for the Singleton Pattern or if you only want access to an object via static factory method.
Example