java枚举混淆
我遇到了以下java代码。这里接口包含两个方法,其中只有一个方法在枚举中实现。据说name()
是自动实现的。我的问题是这怎么可能?我之前没有读过任何关于枚举中自动方法实现的规则。那么这里发生了什么?此外,代码没有给出任何类型的编译时错误。
interface Named {
public String name();
public int order();
}
enum Planets implements Named {
Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune;
// name() is implemented automagically.
public int order() { return ordinal()+1; }
}
I came across the following java code. Here interface contains two methods out of which only one method is implemented in the enum. It is written that name()
is implemented automatically. My question is how is it possible? I have not read any rule regarding automatic method implementation in enum before. So what is happening here? Furthermore the code is not giving any type of compile time error.
interface Named {
public String name();
public int order();
}
enum Planets implements Named {
Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune;
// name() is implemented automagically.
public int order() { return ordinal()+1; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
名称( )
在 Enum 类中定义,它满足您的接口约定,因此您不必定义name()
,除非您想覆盖默认行为。name()
is defined in Enum class which satisfies your interface contract so you don't have to definename()
unless of course you want to override the default behavior.enum
有一个默认方法name()
,仅此而已。它以及其他类似
values()、
valueOf()
和ordinal()
来自 Enum 类。
enum
has a default methodname()
, that's all.It, and others like
values()
,valueOf()
, andordinal()
, come from the Enum class.Java 中的所有枚举都隐式扩展 Enum,它实现了
name()
方法。All enums in Java implicitly extend Enum, which implements the
name()
method.在Java中,有一些为类型预先定义的属性和方法。对于枚举,方法
name()
和对于数组,属性length
都是示例。在您的示例中,方法 name() 将返回“Mercury”、“Venus”、“Earth”等。In Java, there are attributes and methods which are pre-defined for types. For enums, the method
name()
and for arrays, the attributelength
are examples. In your example, the method name() would return "Mercury", "Venus", "Earth" and so on.每个
enum
都派生自抽象类Enum
。该类实现了name()
和提到的ordinal()
等等。看看吧。Every
enum
is dervided from the abstract classEnum<E....>
. That class implements bothname()
and the mentionedordinal()
and some more. Take a look.