Possible Duplicate:
Why can't enum constructors be protected or public in Java?
The following code just demonstrates the use of enum in Java. It has nothing to do with and just sums up the values of the members of that enum.
package enumtest;
enum Sum
{
Pen(10),Pencil(15),Eraser(5);
private int value;
private Sum(int value)
{
this.value=value;
}
public int getValue()
{
return(value);
}
}
final public class Main
{
public static void main(String...args)
{
int sum=0;
for(Sum o:Sum.values())
{
sum+=o.getValue();
}
System.out.println("sum = "+sum);
}
}
It displays sum = 30 on the console. Just one question here. Generally, in a class, constructors are declared public then why can constructors in enum only be declared private? The other modifiers public and protected are not allowed with it. Even declaring it public causes a compile-time error. Why?
You can also declare them without any keyword, e.g. just
Sum(int value).The reason is because Java itself will create the various instances for you, and as Singletons – which is necessary for Enums to work correctly.
publicorprotectedwould imply that or allow additional instances of the same enum to be created by other callers, which would break the Singleton guarantee.