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


当前回答

根据我的说法,我们可以将构造函数声明为私有的 可以在类中使用静态方法获取子类中该类的实例,在类中我们声明构造函数,然后返回类对象。我们将这个方法归为子类 通过使用classname。方法名BCZ是静态方法,我们将获得声明const的类的实例。

其他回答

Yes.

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

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

是的,它可以。我认为这是另一个有用的例子:

//... ErrorType.java
public enum ErrorType {
    X,
    Y,
    Z
}

//... ErrorTypeException.java
import java.util.*;
import java.lang.*;
import java.io.*;

//Translates ErrorTypes only
abstract public class ErrorTypeException extends Exception {
    private ErrorTypeException(){}

    //I don't want to expose thse
    static private class Xx extends ErrorTypeException {}
    static private class Yx extends ErrorTypeException {}
    static private class Zx extends ErrorTypeException {}

    // Want translation without exposing underlying type
    public static Exception from(ErrorType errorType) {
        switch (errorType) {
            case X:
                return new Xx();    
            case Y:
                return new Yx();
            default:
                return new Zx();
        }
    }

    // Want to get hold of class without exposing underlying type
    public static Class<? extends ErrorTypeException> toExceptionClass(ErrorType errorType) {
        switch (errorType) {
            case X:
                return Xx.class;    
            case Y:
                return Yx.class;
            default:
                return Zx.class;
        }
    }
}

在上面的例子中,它阻止抽象类被任何派生类实例化,除了它的静态内部类。抽象类不能是final类,但在这种情况下,私有构造函数使它有效地成为所有非内部类的final类

是的,构造函数可以是私有的。私有构造函数阻止任何其他类实例化私有构造函数的示例

public class CustomHttpClient {
private static HttpClient customHttpClient;

/** A private Constructor prevents any other class from instantiating. */
private CustomHttpClient() {
}}

受到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,并让静态函数返回类实例-请参阅单例模式。但是,非常不鼓励实现单例模式,除非在一些通信只在一个方向上流动的用例中,例如在编写记录器类时

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

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.