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


当前回答

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

其他回答

我以为有人会提到这一点(第二点),但是…私有构造函数有三种用法:

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.

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

为了控制Java对象的实例化,它不允许您创建对象的实例。 它不允许类被子类化 在实现单例模式时,这有一个特殊的优势,它使用私有构造函数,并控制为整个应用程序创建实例。 当你想要一个定义了所有常量的类,并且不再需要它的实例时,我们将这个类声明为私有构造函数。

受到Robert C. Martin的“Clean Code”的启发,我整理了一个例子:

/**
When overloading constructors, it is best practise to only allow the use of
different constructors than the standart one by explicitly enforcing the 
useage of a static function to highlight the use of the overloaded constructor

in example:
Animal a = Animal.CreateInsectOrArachnia(2, "black", 8); //hatch a black widow
*/


class Animal
{
   private int size;
   private String color;
   private int legs;

   public Animal(int size, String color)
   {
       this.size = size;
       this.color = color;
       this.legs = 4;
   }

   //will prevent the instanciation of Animal with this constructor
   private Animal(int size, String color, int legs)
   {
       this.size = size;
       this.color = color;
       this.legs = legs;
   }


   public static Animal CreateInsectOrArachnia(int size, String color, int legs)
   {
    return new Animal (size, color, legs);
   }

}

Martins明确指出,应该阻止用户访问“标准构造函数”以外的构造函数,并应该强制使用静态初始化函数,以强调“你所做的可能没有错,但它与该类的预期使用不同”。

[他没有使用这个确切的措辞,我试图把它挤进这个定义-对不起,罗伯特:^)]

作为旁注,完全可以将类中唯一的构造函数(即标准构造函数)完全声明为private,并让静态函数返回类实例-请参阅单例模式。但是,非常不鼓励实现单例模式,除非在一些通信只在一个方向上流动的用例中,例如在编写记录器类时

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

Yes.

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