以下是要翻译的内容: 下面的Java枚举类的主体是如何工作的?

huangapple go评论72阅读模式
英文:

How does the body of the below java enum class work?

问题

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

我已经阅读了关于Java枚举的完整Oracle文档我了解它的工作原理和基础知识但是我对上面枚举类的主体部分一无所知
Player()Enemy()是常量吗还是函数
另外ID.Player()会返回什么
英文:
public enum ID {
 Player(),
 Enemy();
}

I've read the entire oracle documentation for java enum, I know how it works and all the basics but I have no clue about the body of the above enum class
Are Player () , Enemy () constants ? functions ?
Also what would this return ID.Player();

答案1

得分: 8

正如普通类一样,如果不声明显式构造函数,枚举也会获得一个默认的无参构造函数。

语言规范【链接】中说道:

> 在没有构造函数声明的枚举声明中,会隐式声明一个默认构造函数。默认构造函数是私有的,没有形式参数,并且没有throws子句。

在此之前稍早的部分,它还提到:

> 枚举常量后面可以跟随参数,这些参数会传递给枚举的构造函数... 如果省略了参数,则假定为空参数列表。

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

英文:

Just as with regular classes, you get a default no-arg constructor with enums if you don't declare an explicit constructor.

The language spec 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.

Slightly before that, it also says:

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

As such, these are just enum constants, explicitly invoking that implicit constructor. It's exactly the same as if you omitted the ().

huangapple
  • 本文由 发表于 2020年5月31日 02:54:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/62107281.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定