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


当前回答

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

其他回答

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

私有构造函数防止调用者显式实例化类 请参阅PrivateConstructor的进一步信息

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

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

//... 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类

Yes.

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

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

public class CustomHttpClient {
private static HttpClient customHttpClient;

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