gpt4 book ai didi

java - 枚举的各个值可以实现接口(interface)吗

转载 作者:行者123 更新时间:2023-12-02 04:05:39 39 4
gpt4 key购买 nike

enum 可以实现接口(interface)。某些值是否可以实现接口(interface)?我正在考虑的用例是一个标记接口(interface),如下所示:

interface Foo {}
interface Bar {}

enum Widgets {
FOO implements Foo,
BAR_1 implements Bar,
BAR_2 implements Bar
}

它不能在 Java 1.8 下编译。我知道在内部,为 FOO 和 BAR_1 创建了单独的类,所以这似乎是可能的,但我可以很容易地看到标准不支持它。

类似的应该有效的东西是

interface Widgets;
enum Foo implements Widgets { FOO };
enum Bar implements Widgets { BAR_1, BAR_2 };

这有一个缺点,我不能只执行 Widgets.values() 并获取所有小部件。

最佳答案

Java Language Specification

The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type. The class body is governed by the usual rules of anonymous classes; in particular it cannot contain any constructors. Instance methods declared in these class bodies may be invoked outside the enclosing enum type only if they override accessible methods in the enclosing enum type (§8.4.8).

匿名类只能扩展(或实现)新实例创建表达式中指定的类型,在本例中是您的enum类型。因此,您不能让它另外实现接口(interface)。

<小时/>

以下内容

enum Foo {
CONSTANT
}

被编译成类似的东西

class Foo extends Enum<Foo> {
private Foo() {/* calling Enum superconstructor */}
public static final Foo CONSTANT = new Foo();
}

如果您希望常量具有主体(以覆盖或声明某些方法)

enum Foo {
CONSTANT {
public String toString() {
return name().toUpperCase();
}
}
}

变成类似的东西

class Foo extends Enum<Foo> {
private Foo() {/* calling Enum superconstructor */}
public static final Foo CONSTANT = new Foo() { // no way to express an additional interface
public String toString() {
return name().toUpperCase();
}
};
}

关于java - 枚举的各个值可以实现接口(interface)吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34074768/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com