There is a statement "The enum constructor can be invoked outside of enum." in JAVA SE:Programming Complete Course. I know enum constructors can either have private or default access modifier. When it's private we can't access enum constructor outside of the enum. We may access enum constructor outside of enum when it has default access modifier. But I couldn't find any example of how to access enum constructors outside of the enum. Could you please give an example for this case?
-
You can't. The statement is simply wrong. Enum constructors without a modifier are implicitly private.Andy Turner– Andy Turner2021-04-27 12:57:30 +00:00Commented Apr 27, 2021 at 12:57
-
It's wrong. Those 3 entries (hot, warm, cold) are the only instances. An enum represents a finite set of possible instances. If you could instantiate more of them arbitrarily then the whole idea is pointless.Michael– Michael2021-04-27 12:58:22 +00:00Commented Apr 27, 2021 at 12:58
2 Answers
From the language specification:
It is a compile-time error if a constructor declaration in an enum declaration is public or protected (§6.6).
...
In an enum declaration, a constructor declaration with no access modifiers is private.
So, enum constructors are always private: you can't invoke an enum constructor outside the enum itself; and you can only invoke another a constructor via this(...) as the first statement of one of the enum constructors, not as new MyEnumType(...).
2 Comments
From Java Documentation:
https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself
Package-private means with no access modifier, but in this case the Enum constructor implicitly will still have only private access.
