Why do we need (i.e. generally advised) to use 'private' constructors for 'enum' types in Java (1.5)? .... Then, why do we have the option to use public constructors?
Steven Bell
Ranch Hand
Joined: Dec 29, 2004
Posts: 1071
posted
0
At a guess.
Enums in 1.5 are just a special type of class. Because there is no way to limit the visibility of a constructor in any other class it was to difficult, without enough benifit, to force the constructors to be private.
Like I said, just a guess.
Mahesh Kumaraguru
Ranch Hand
Joined: Jun 01, 2005
Posts: 95
posted
0
Originally posted by Mallesham Karnati: Why do we need (i.e. generally advised) to use 'private' constructors for 'enum' types in Java (1.5)? .... Then, why do we have the option to use public constructors?
states Enum protected Enum(String name, int ordinal) Sole constructor. Programmers cannot invoke this constructor. It is for use by code emitted by the compiler in response to enum type declarations. ".
Enum constructor is private so that we do not instantiate may be. But check it out even if you do not keep it private it should work.
Mahesh Kumaraguru
Ranch Hand
Joined: Jun 01, 2005
Posts: 95
posted
0
Originally posted by Santana Iyer: Enum constructor is private so that we do not instantiate may be. But check it out even if you do not keep it private it should work.
Your second sentence "But check it out even if you do not keep it private it should work" is not clear. Are you talking of extending the enum class ?
Joyce Lee
Ranch Hand
Joined: Jul 11, 2003
Posts: 1392
posted
0
Hi Mahesh,
The constructor which Santana was saying is the one that is declared inside the enum block, not the protected constructor of Enum class defined in the API. The constructor for an enum type is implicitly private; that is, with or without the modifier "private" being specified, the constructor is always private.
For example:
If a modifier other than "private" is placed before Day constructor, a compiler error will be generated.
Joyce
Mallesham Karnati
Ranch Hand
Joined: May 11, 2005
Posts: 40
posted
0
--------------------------------------------------- public enum Day { ... public Day() { } // illegal protected Day() { } // illegal private Day() { } // ok Day() { } // ok - implicit private ...} ------------------------------------------------------
Joyce, In the above code, is Public Day(){} Illegal or not usually recommended? I am just curious to know. Regards, Mallesham