Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private enum constructor

Tags:

java

enums

The constructor for this enum is private. What does that mean?

public enum SLocale {      EN_US(Locale.US, "www.abc.com", "www.edc.com", "www.vvv.com",             "www.earn.com");      List<String> domains;     Locale loc;     IMap map;      private SLocale(Locale loc, String... domains) {         this.domains = Arrays.asList(domains);         this.loc = loc;         this.siteMap = Factory.getMap(loc);     }      public List<String> getDomains() {         return domains;     }      public Locale getLoc() {         return loc;     }      public ISiteMap getMap() {         return map;     } } 
like image 453
pushya Avatar asked Aug 18 '11 19:08

pushya


People also ask

Can an enum have a constructor?

enum can contain a constructor and it is executed separately for each enum constant at the time of enum class loading.

Are enum constructors private by default?

The 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 .

Does enum class need constructor?

A type defined with enum class or enum struct is not a a class but a scoped enumeration and can not have a default constructor defined.

Should enum be private?

An enum is a type, not a data member. You should make it public if users of the class need to know about it; otherwise, make it private. A typical situation where users need to know about it is when it's used as the type of an argument to a public member function.


2 Answers

A private constructor only allows objects to be constructed from within the class definition. Being an enum, it is easy to get confused, so I usually find it easier to think of an enum as a class with some special features. So when you write:

SLocale.EN_US 

Basically, the parameters

Locale.US, "www.abc.com", "www.edc.com", "www.vvv.com", "www.earn.com" 

will be passed to the private constructor so that the enum can be instantiated. Enum constructors have to be private.

like image 153
Dhruv Gairola Avatar answered Sep 18 '22 23:09

Dhruv Gairola


From: http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.

You cannot actually have a public enum constructor.

like image 25
Beez Avatar answered Sep 17 '22 23:09

Beez