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


当前回答

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

其他回答

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

public class CustomHttpClient {
private static HttpClient customHttpClient;

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

Yes.

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

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

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

Yes.

这样您就可以控制类的实例化方式。如果将构造函数设为私有,然后创建一个返回类实例的可见构造函数方法,则可以限制创建的数量(通常是保证只有一个实例)或回收实例或其他与构造相关的任务。

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

也可以将它用于没有实例成员或属性,只有静态成员或属性的类——就像在实用函数类中一样。

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

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

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