Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a enum have a package-private constructor?

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

like image 308
Tobias Avatar asked Oct 12 '11 23:10

Tobias


People also ask

Can enum have private constructor Java?

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.

Are enum constructors private by default?

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.

Can enum have private variables?

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 .

What is package private constructor?

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.


1 Answers

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.

like image 126
ColinD Avatar answered Sep 23 '22 00:09

ColinD