Since an enum constructor can only be invoked by its constants, why is it then allowed to be package-private?
Now, you know that Enum can have a constructor in Java that can be used to pass data to Enum constants, just like we passed action here. Though Enum constructor cannot be protected or public, it can either have private or default modifier only.
Enum cannot have a default no-argument constructor and all its constructors (if any) are private; therefore, it is redundant to specify them explicitly. Note that the enum constructor classes are implicit and do not require new keyword.
Enum FieldsThe enum constructor must be private . You cannot use public or protected constructors for a Java enum . If you do not specify an access modifier the enum constructor it will be implicitly private .
Private constructors allow us to restrict the instantiation of a class. Simply put, they prevent the creation of class instances in any place other than the class itself.
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
orprotected
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With