Since an enum constructor can only be invoked by its constants, why is it then allowed to be package-private?
Why can a enum have a package-private constructor?
18.3k views Asked by Tobias At
2
There are 2 answers
4
On
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 constructor actually isn't package-private... it's implicitly
private
the way interface methods are implicitlypublic
even if you don't add the keyword.The relevant section of the JLS (§8.8.3) states: