简体   繁体   中英

Java enum constructors

声明在这里

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?

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(...) .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM