Java中的构造函数可以是私有的吗?
构造函数可以是私有的吗?私有构造函数有什么用?
Can a constructor be private? How is a private constructor useful?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
构造函数可以是私有的吗?私有构造函数有什么用?
Can a constructor be private? How is a private constructor useful?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(16)
受到 Robert C. Martin 的“干净代码”的启发,我摆弄了一个例子:
Martins 明确指出应该阻止用户访问“标准构造函数”之外的构造函数,并且应该强制使用静态初始化函数来强调“你所做的”可能没有错,但它与此类的预期用法不同”
[他没有使用这个确切的措辞,我试图将其压缩到这个定义中 - 对不起罗伯特:^)]
作为旁注,完全声明是完全可以的类中唯一的构造函数(也称为标准构造函数)是私有的,并且有一个静态函数返回一个类实例 - 请参阅单例模式。强烈建议不要实现单例模式,除了某些通信仅朝一个方向流动的用例,比如编写记录器类时
Inspired by Robert C. Martin's "Clean Code", example I fiddled together:
Martins explicitly states that users should be prevented from accessing constructors other than the "standart constructor" and should be forced to use static initialisation functions to underline that "what you do may not be wrong but it differs from expected useage of this class"
[he did not use this exact wording, i tried to squeeze it into this definition - sorry Robert :^) ]
As a side note, it is totally okay to completely declare the only constructor in a class (aka standart-constructor) as private and have a static function return a class instance - see singleton pattern. it is highly discouraged to implement a singleton pattern tho, except maybe for some use-cases where communication only flows in one direction, f.e. when writing a logger class
拥有私有构造函数背后的基本思想是限制 JVM 从外部实例化类,但如果一个类具有参数构造函数,那么它就推断出该类是有意实例化的。
Basic idea behind having a private constructor is to restrict the instantiation of a class from outside by JVM, but if a class having a argument constructor, then it infers that one is intentionally instantiating.
根据我的说法,我们可以将构造函数声明为私有,而且我们
可以通过在类中使用静态方法来获取子类中该类的实例,在该类中声明构造函数,然后返回类对象。我们将此方法分类为子类
通过使用 classname.method 名称 bcz,它是静态方法,我们将获得声明 const 的类的实例。
According to me we can declare constructor as a private and also we
can get the instance of that class in the subclass by using static method in class in which we declare constructor and then return class object. we class this method from to the sub class
by using
classname.method
name bcz it is static method and the we will get the instance of class in which we declare const.是的,构造函数可以是私有的。这有不同的用途。其中一种用途是用于单一设计反模式 ,我建议您不要使用。另一种更合法的用途是委托构造函数;您可以有一个构造函数,该构造函数采用许多不同的选项,这实际上是一个实现细节,因此您将其设为私有,但随后其余的构造函数委托给它。
作为委托构造函数的示例,以下类允许您保存值和类型,但它只允许您对类型的子集执行此操作,因此需要将通用构造函数设为私有以确保仅使用允许的类型。公共的私有构造函数有助于代码重用。
编辑
几年后再看这个答案,我想指出这个答案既不完整,也有点极端。单例确实是一种反模式,通常应尽可能避免;然而,除了单例之外,私有构造函数还有很多用途,我的答案只提到了一种。
给出更多使用私有构造函数的情况:
创建一个不可实例化的类,它只是相关静态函数的集合(这基本上是一个单例,但如果它是无状态的并且静态函数严格对参数进行操作这并不是像我之前所建议的那样不合理的方法,而不是基于类状态,尽管当实现需要大量依赖项或其他形式的依赖项时,使用依赖项注入的接口通常可以更轻松地维护 API 是
当有多种不同的方法来创建对象时,私有构造函数可能会让您更容易理解构造它的不同方法(例如,这对您来说更具可读性
new ArrayList(5)
或ArrayList.createWithCapacity(5)
、ArrayList.createWithContents(5)
、ArrayList.createWithInitialSize(5)
)。换句话说,私有构造函数允许您提供名称更容易理解的工厂函数,然后将构造函数设为私有可确保人们只使用更不言而喻的名称。这也通常与构建器模式一起使用。例如:Yes, a constructor can be private. There are different uses of this. One such use is for the singleton design anti-pattern, which I would advise against you using. Another, more legitimate use, is in delegating constructors; you can have one constructor that takes lots of different options that is really an implementation detail, so you make it private, but then your remaining constructors delegate to it.
As an example of delegating constructors, the following class allows you to save a value and a type, but it only lets you do it for a subset of types, so making the general constructor private is needed to ensure that only the permitted types are used. The common private constructor helps code reuse.
Edit
Looking at this answer from several years later, I would like to note that this answer is both incomplete and also a little bit extreme. Singletons are indeed an anti-pattern and should generally be avoided where possible; however, there are many uses of private constructors besides singletons, and my answer names only one.
To give a couple more cases where private constructors are used:
To create an uninstantiable class that is just a collection of related static functions (this is basically a singleton, but if it is stateless and the static functions operate strictly on the parameters rather than on class state, this is not as unreasonable an approach as my earlier self would seem to suggest, though using an interface that is dependency injected often makes it easier to maintain the API when the implementation requires larger numbers of dependencies or other forms of context).
When there are multiple different ways to create the object, a private constructor may make it easier to understand the different ways of constructing it (e.g., which is more readable to you
new ArrayList(5)
orArrayList.createWithCapacity(5)
,ArrayList.createWithContents(5)
,ArrayList.createWithInitialSize(5)
). In other words, a private constructor allows you to provide factory function's whose names are more understandable, and then making the constructor private ensures that people use only the more self-evident names. This is also commonly used with the builder pattern. For example:我预计有人会提到这一点(第二点),但是..私有构造函数有三种用途:
在以下情况下防止在对象外部实例化:
.
防止子类继承(扩展)。如果您只创建一个私有构造函数,则任何类都无法扩展您的类,因为它无法调用
super()
构造函数。这是final
的某种同义词,
I expected that someone would've mentioned this (the 2nd point), but.. there are three uses of private constructors:
to prevent instantiation outside of the object, in the following cases:
.
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 forfinal
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.
是的,可以。存在私有构造函数是为了防止类被实例化,或者因为构造仅在内部发生,例如工厂模式。请参阅此处了解更多信息。
Yes it can. A private constructor would exist to prevent the class from being instantiated, or because construction happens only internally, e.g. a Factory pattern. See here for more information.
是的。
这样您就可以控制类的实例化方式。如果将构造函数设为私有,然后创建一个返回类实例的可见构造函数方法,则可以执行诸如限制创建数量(通常保证只有一个实例)或回收实例或其他与构造相关的任务之类的操作。
执行
new x()
永远不会返回null
,但使用工厂模式,您可以返回null
,甚至返回不同的子类型。您也可以将它用于没有实例成员或属性、只有静态成员或属性的类 - 就像在实用程序函数类中一样。
Yes.
This is so that you can control how the class is instantiated. If you make the constructor private, and then create a visible constructor method that returns instances of the class, you can do things like limit the number of creations (typically, guarantee there is exactly one instance) or recycle instances or other construction-related tasks.
Doing
new x()
never returnsnull
, but using the factory pattern, you can returnnull
, or even return different subtypes.You might use it also for a class which has no instance members or properties, just static ones - as in a utility function class.
好吧,如果类中的所有方法都是静态的,那么私有构造函数是一个好主意。
Well, if all of your methods in a class are static, then a private constructor is a good idea.
是的。类可以有私有构造函数。即使抽象类也可以有私有构造函数。
通过将构造函数设置为私有,我们可以防止该类被实例化以及该类的子类化。
以下是私有构造函数的一些用法:
Yes. Class can have private constructor. Even abstract class can have private constructor.
By making constructor private, we prevent the class from being instantiated as well as subclassing of that class.
Here are some of the uses of private constructor :
由于以下原因,可以在 Java 中定义私有构造函数
要控制 Java 对象的实例化,它不允许您创建对象的实例。
它不会允许类被子类化
这在实现单例模式时有一个特殊的优势,使用私有构造函数并可以控制为整个应用程序创建实例。
当你想要一个定义了所有常量的类并且不再需要它的实例时,我们将该类声明为私有构造函数。
当你想要
Private Constructors can be defnied in the Java for the following reasons
To have control on the instantiation of the Java objects, it wont allow you to create an instance of an object.
It wont allow the class to be Subclassed
This has a special advantage when implementing the singleton Pattern, Private contstructors are used for it and have a control on the creating the instance for the whole application.
when you want to have a class with all constants defined and Does not require its instance any more, then we declare that class as a private constructor.
是的。
私有构造函数用于防止实例初始化,例如您在java中使用的Math Final类。 Singleton也使用私有构造函数
Yes.
A private constructor is used to prevent instance initializing, such as the Math final class you use in java. Singleton also use private constructor
是的,类可以有一个私有构造函数。需要它来禁止从其他类访问构造函数并在定义的类中保持其可访问性。
为什么您希望您的类的对象仅在内部创建?可以出于任何原因执行此操作,但一个可能的原因是您想要实现单例。单例是一种只允许创建类的一个实例的设计模式,这可以通过使用私有构造函数来完成。
Yes, class can have a private constructor. It is needed as to disallow to access the constructor from other classes and remain it accessible within defined class.
Why would you want objects of your class to only be created internally? This could be done for any reason, but one possible reason is that you want to implement a singleton. A singleton is a design pattern that allows only one instance of your class to be created, and this can be accomplished by using a private constructor.
是的,构造函数可以是私有的。私有构造函数阻止任何其他类实例化私有构造函数的示例
yes a constructor can be private. A private Constructor prevents any other class from instantiating example of private constructor
是的,可以。我认为这是另一个有用的例子:
在上面的例子中,它防止抽象类被除静态内部类之外的任何派生类实例化。抽象类不能是最终类,但在这种情况下,私有构造函数使其对所有非内部类的类有效地最终化
Yes it can. I consider this another example of it being useful:
In the case here above, it prevents the abstract class from being instantiated by any derived class other than it's static inner classes. Abstract classes cannot be final, but in this case the private constructor makes it effectively final to all classes that aren't inner classes
私有构造函数阻止调用者显式实例化类
请参阅有关 PrivateConstructor 的更多信息
Private constructors prevent a class from being explicitly instantiated by callers
see further information on PrivateConstructor
是的,它用于防止实例化和随后的覆盖。这最常用于单例类中。
Yes and it is used to prevent instantiation and subsequently overriding. This is most often used in singleton classes.