Java:为什么构造函数具有访问修饰符?

Ahm*_*mad 1 java constructor

例如一个类:

//class1
class A {
    private A() {  } // why would I make it private?
    public A(int) {  } //why isn't it implicitly public?
}
//class2
class B {

    public static void main(String[] args) {
        //A a = new A();
    }
}
Run Code Online (Sandbox Code Playgroud)

构造函数实例化一个类,为什么它有访问修饰符?是否有必要声明构造函数是私有的

Pet*_*rey 6

构造函数实例化一个类,为什么它有访问修饰符?

可以使用修改器,以便控制对象的构造位置.

是否有必要声明构造函数是私有的?

假设你有一个像工厂的方法

class A {
    private A(int n)  { }

    public static A create(int n) {
        return new A(n);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者你有一个应该直接调用的共享构造函数.

class B {
    public B(int n) {
        this(n, "");
    }
    public B(String str) {
        this(0, str);
    }
    private B(int n, String str) { }
}
Run Code Online (Sandbox Code Playgroud)

或者你有一个单身人士

final class Singleton {
    Singleton INSTANCE = new Singleton();
    private Singleton() { }
}
Run Code Online (Sandbox Code Playgroud)

但是我更喜欢使用enum带有private构造函数的.

enum Singleton {
    INSTANCE;
}
Run Code Online (Sandbox Code Playgroud)

或者你有一个Utility类

final class Utils {
    private Utils() { /* don't create one */ }

    public static int method(int n) { }
}
Run Code Online (Sandbox Code Playgroud)

但是在这种情况下我更喜欢使用枚举

enum Utils {
    /* no instances */;

    public static int method(int n) { }
}
Run Code Online (Sandbox Code Playgroud)

注意:如果在final类上使用私有构造函数,仍可以使用嵌套类或反射创建实例.如果使用a enum,则无法轻易/意外地创建实例.

警告:您可以创建enum使用的实例Unsafe


必须注意enum构造函数中的注意事项private

class BuySell {
    BUY(+1), SELL(-1);

    private BuySell(int dir) { }
}
Run Code Online (Sandbox Code Playgroud)

您不必private明确指定它,因为这是默认设置.