java枚举混淆

发布于 2024-12-20 05:30:28 字数 428 浏览 3 评论 0原文

我遇到了以下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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

刘备忘录 2024-12-27 05:30:28

名称( ) 在 Enum 类中定义,它满足您的接口约定,因此您不必定义 name() ,除非您想覆盖默认行为。

name() is defined in Enum class which satisfies your interface contract so you don't have to define name() unless of course you want to override the default behavior.

你在看孤独的风景 2024-12-27 05:30:28

enum 有一个默认方法 name(),仅此而已。

它以及其他类似 values()、valueOf()ordinal() 来自 Enum 类

enum has a default method name(), that's all.

It, and others like values(), valueOf(), and ordinal(), come from the Enum class.

无所谓啦 2024-12-27 05:30:28

Java 中的所有枚举都隐式扩展 Enum,它实现了 name() 方法。

公共最终字符串名称()

返回此枚举常量的名称,与其枚举声明中所声明的完全相同。

All enums in Java implicitly extend Enum, which implements the name() method.

public final String name()

Returns the name of this enum constant, exactly as declared in its enum declaration.

静赏你的温柔 2024-12-27 05:30:28

在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 attribute length are examples. In your example, the method name() would return "Mercury", "Venus", "Earth" and so on.

£噩梦荏苒 2024-12-27 05:30:28

每个enum 都派生自抽象类Enum。该类实现了 name() 和提到的 ordinal() 等等。看看吧。

Every enum is dervided from the abstract class Enum<E....>. That class implements both name() and the mentioned ordinal() and some more. Take a look.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文