简体   繁体   中英

Why can a enum have a package-private constructor?

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

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

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

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 public or protected .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM