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


当前回答

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

其他回答

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

public class CustomHttpClient {
private static HttpClient customHttpClient;

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

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类

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