Java 中的构造函数可以是私有的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2816123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:11:07  来源:igfitidea点击:

Can a constructor in Java be private?

javaconstructorprivate

提问by Rajesh

Can a constructor be private? How is a private constructor useful?

构造函数可以是私有的吗?私有构造函数有什么用?

回答by lavinio

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 returns null, but using the factory pattern, you can return null, or even return different subtypes.

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

You might use it also for a class which has no instance members or properties, just static ones - as in a utility function class.

您也可以将它用于没有实例成员或属性,只有静态成员的类 - 如在实用程序函数类中。

回答by GustyWind

Private constructors prevent a class from being explicitly instantiated by callers see further information on PrivateConstructor

私有构造函数可防止调用者显式实例化类,请参阅PrivateConstructor 上的更多信息

回答by Michael Aaron Safyan

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.

作为委托构造函数的示例,以下类允许您保存值和类型,但它只允许您为类型的子集执行此操作,因此需要将通用构造函数设为私有以确保仅使用允许的类型. 公共私有构造函数有助于代码重用。

public class MyClass {
     private final String value;
     private final String type;

     public MyClass(int x){
         this(Integer.toString(x), "int");
     }

     public MyClass(boolean x){
         this(Boolean.toString(x), "boolean");
     }

     public String toString(){
         return value;
     }

     public String getType(){
         return type;
     }

     private MyClass(String value, String type){
         this.value = value;
         this.type = type;
     }
}

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:

再举几个使用私有构造函数的情况:

  1. 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).

  2. 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)or ArrayList.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:

    MyClass myVar = MyClass
        .newBuilder()
        .setOption1(option1)
        .setOption2(option2)
        .build();
    
  1. 创建一个不可实例化的类,它只是相关静态函数的集合(这基本上是一个单例,但如果它是无状态的并且静态函数严格根据参数而不是类状态运行,这不像我的方法那样不合理早期的 self 似乎建议,尽管当实现需要大量依赖或其他形式的上下文时,使用依赖注入的接口通常可以更容易地维护 API)。

  2. 当有多种不同的方式来创建对象时,私有构造函数可以让您更容易理解不同的构造方式(例如,哪种方式对您来说更易读,new ArrayList(5)或者ArrayList.createWithCapacity(5), ArrayList.createWithContents(5), ArrayList.createWithInitialSize(5))。换句话说,私有构造函数允许您提供名称更易于理解的工厂函数,然后将构造函数设为私有可确保人们只使用更不言而喻的名称。这也常与构建器模式一起使用。例如:

    MyClass myVar = MyClass
        .newBuilder()
        .setOption1(option1)
        .setOption2(option2)
        .build();
    

回答by Feanor

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 herefor more information.

是的,它可以。将存在私有构造函数以防止类被实例化,或者因为构造仅在内部发生,例如工厂模式。请参阅此处了解更多信息。

回答by Vaishak Suresh

Yes and it is used to prevent instantiation and subsequently overriding. This is most often used in singleton classes.

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

回答by Bozho

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:

    • 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.

  • 防止在对象外实例化,在以下情况下:

    • 单身人士
    • 工厂方法
    • 仅静态方法(实用程序)类
    • 仅常量类
  • 以防止子分类(扩展)。如果您只创建一个私有构造函数,则没有类可以扩展您的类,因为它不能调用super()构造函数。这是某种同义词final

  • 重载构造函数 - 由于方法和构造函数重载,有些可能是私有的,有些可能是公共的。特别是当您在构造函数中使用非公共类时,您可以创建一个公共构造函数来创建该类的实例,然后将其传递给私有构造函数。

回答by gmhk

Private Constructors can be defnied in the Java for the following reasons

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

  1. To have control on the instantiation of the Java objects, it wont allow you to create an instance of an object.

  2. It wont allow the class to be Subclassed

  3. 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.

  4. 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.

  1. 为了控制 Java 对象的实例化,它不允许您创建对象的实例。

  2. 它不会允许类被子类化

  3. 这在实现单例模式时有一个特殊的优势,私有构造函数用于它并且可以控制为整个应用程序创建实例。

  4. 当你想要一个定义了所有常量的类并且不再需要它的实例时,我们将该类声明为私有构造函数。

回答by ryf9059

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

私有构造函数用于防止实例初始化,例如您在 java 中使用的 Math final 类。单例也使用私有构造函数

回答by Phani

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.

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

回答by SBTec

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.

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