java - 下面的 java 枚举类的主体是如何工作的?

标签 java class enums constants

public enum ID {
 Player(),
 Enemy();
}

我已经阅读了 Java 枚举的整个 oracle 文档,我知道它是如何工作的以及所有基础知识,但我对上述枚举类的主体一无所知 Player () , Enemy () 是常量吗?功能 ? 还有这会返回什么 ID.Player();

最佳答案

与常规类一样,如果您不声明显式构造函数,您将获得一个带有枚举的默认无参数构造函数。

语言规范 says :

In an enum declaration with no constructor declarations, a default constructor is implicitly declared. The default constructor is private, has no formal parameters, and has no throws clause.

在这之前,它还说:

An enum constant may be followed by arguments, which are passed to the constructor of the enum ... If the arguments are omitted, an empty argument list is assumed.

因此,这些只是枚举常量,显式调用隐式构造函数。这与省略 () 完全相同。

关于java - 下面的 java 枚举类的主体是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62107281/

相关文章:

java - 对于此代码,使用 Java 在 SPOJ 中获取 NZEC 错误

java - Android - 将 TCP 客户端转换为 UDP 客户端

java - 如何在 Java 中对 MongoDB 查询结果进行排序?

Python - 如何正确设置类的层次结构?

c++ - 从类模块检索信息以在 switch 语句中输出的问题

ios - 警告 : Incompatible integer to pointer conversion when using NS_ENUM types

rust - Rust 中无需使用双重匹配语句即可将整数与枚举情况进行匹配

java - 旋转画线 Java Applet

c++ - : expected constructor, 析构函数错误,或者 ‘::’ token 之前的类型转换

C++ 转换运算符重载、枚举、整数和字符