简体   繁体   English

Java 枚举构造函数

[英]Java enum constructors

声明在这里

There is a statement "The enum constructor can be invoked outside of enum."有一条语句“可以在枚举之外调用枚举构造函数。” in JAVA SE:Programming Complete Course.在 JAVA SE:编程完成课程。 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).如果枚举声明中的构造函数声明是公共的或受保护的(第 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(...) .并且您只能通过this(...)作为枚举构造函数之一的第一条语句调用另一个构造函数,而不是new MyEnumType(...)

From Java Documentation:来自 Java 文档:

https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html 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.包私有意味着没有访问修饰符,但在这种情况下,枚举构造函数隐式仍然只有私有访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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