Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why We Use Non Modified Constructor in Enum in Java

I have seen a java code where I see a non-modified constructor in an enum. Can anyone tell me why it is like that?

public enum myEnum{

  myEnum()
   {
       System.out.println("Hello World");
   }
}
like image 725
Newaz Sharif Avatar asked Jun 01 '26 21:06

Newaz Sharif


1 Answers

Assuming you mean why there is no access modifier for the constructor, that's because

In an enum declaration, a constructor declaration with no access modifiers is private.

and

It is a compile-time error if a constructor declaration in an enum declaration is public or protected (§6.6).

It's redundant to specify private, so some people don't.

like image 143
Sotirios Delimanolis Avatar answered Jun 04 '26 09:06

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!