constructor - What makes enum in java non instantiable? -


i know enum

enum year {    first, second, third, fourth; } 

gets converted into

final class year extends enum<year> {         public static final year first = new year();         public static final year second = new year();         public static final year third = new year();         public static final year fourth = new year(); } 

when tried instantiate enum (not class) got compile time error as:

error: enum types may not instantiated         year y = new year(); 

as per knowledge private constructor makes class non instantiable. , thought compiler providing private constructor. again got confused when saw can define constructor enum default modifier , still cannot create object of type enum.

enum year {         first, second, third, fourth;         year()         {         } }  class example {         public static void main(string[] args)         {                 year y = new year();         } } 

my doubt is, if not constructors makes enum in java non instantiable?

it specified in java language specification:

8.9. enum types

...

an enum type has no instances other defined enum constants. compile-time error attempt explicitly instantiate enum type (§15.9.1).

hence compiler ensures requirement met. since compiler "knows" type enum, can distinguish between enum year , final class year.

also, no access modifier allowed enum constructor:

8.9.2. enum body declarations

...

it compile-time error if constructor declaration in enum declaration public or protected.

...

in enum declaration, a constructor declaration no access modifiers private.

so, in practice, enum constructor looks package-scoped (no access modifier), private.

finally, same section states

in enum declaration no constructor declarations, default constructor implicitly declared. the default constructor private, has no formal parameters, , has no throws clause.

this makes enum non-instantiable if no constructor explicitly declared.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -