Ankit Garg wrote:Enum constructor has to be private. This is to stop any construct to create an instance of the enum. That would defeat the purpose of enums. How would you feel if you create an enum of fruits containing Apple, orange and Banana. And someone creates another instance of the enum which is Carrot. This is why enum constructors are private...
Christophe Verré wrote:
I'm still confuse, why default is allowed?
8.8.3 Constructor Modifiers
It is a compile-time error if the constructor of an enum type (§8.9) is declared public or protected.
Ruben Soto wrote:Yes, but what is the reason default is allowed? That still lets any classes in the same package as the enum use the enum's constructor, doesn't it?
Christophe Verré wrote:Did you look at my post ?
"It is a compile-time error if the constructor of an enum type (§8.9) is declared public or protected.".
Does it say that a constructor must not have the default access ?
1. If no constructor is explicitly provided, a default private constructor will be created.
2. Constructors access may be private or default
I don't think I ever said in my post that a constructor can't have default access.
Ruben Soto wrote:I understand that Punit (if you don't provide a constructor for an enum, the default constructor will have private access.) But still default access is allowed in constructors that you code. I'm wondering why.
Ruben Soto wrote:Ah, that's what's going on! Thank you, Punit. Kind of weird that you are still allowed to code it with default access. I guess they did it that way as a convenience feature maybe.