java 为什么枚举可以有一个包私有构造函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7747948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:14:54  来源:igfitidea点击:

Why can a enum have a package-private constructor?

javaenumspackage-private

提问by Tobias

Since an enum constructor can only be invoked by its constants, why is it then allowed to be package-private?

既然枚举构造函数只能由它的常量调用,那么为什么允许它是包私有的呢?

回答by ColinD

The constructor actually isn't package-private... it's implicitly privatethe way interface methods are implicitly publiceven if you don't add the keyword.

构造函数实际上不是包私有的......即使您不添加关键字,它也是隐式private接口方法的隐式方式public

The relevant section of the JLS (§8.8.3) states:

JLS ( §8.8.3)的相关部分指出:

If no access modifier is specified for the constructor of a normal class, the constructor has default access.

If no access modifier is specified for the constructor of an enum type, the constructor is private.

It is a compile-time error if the constructor of an enum type (§8.9) is declared publicor protected.

如果没有为普通类的构造函数指定访问修饰符,则构造函数具有默认访问权限。

如果没有为枚举类型的构造函数指定访问修饰符,则构造函数为private

如果声明了枚举类型(第 8.9 节)的构造函数publicprotected.

回答by Bohemian

It's a quirk of the language: enum constructors are implicitly private.

这是该语言的一个怪癖:枚举构造函数是隐式私有的。

Interestingly, if you declare a package-visible enum constructor, like this:

有趣的是,如果你声明一个包可见的枚举构造函数,像这样:

public enum MyEnum {
    A(0),
    B(1);

    private final int i;

    MyEnum(int i) {
        this.i = i;
    }

    public int getI() {
        return i;
    }
}

you can't refer to it from another class in the package. If you try, you get the compiler error:

你不能从包中的另一个类引用它。如果你尝试,你会得到编译器错误:

Cannot instantiate the type MyEnum

无法实例化 MyEnum 类型