Why can a enum have a package-private constructor?

荒凉一梦 提交于 2019-11-26 17:41:38

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/7747948/why-can-a-enum-have-a-package-private-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!