问题描述
我想知道为什么在Java语言中,类
不能扩展枚举
。
我不是在说一个枚举
扩展一个枚举
(可以'不要做,因为java没有多重继承,而枚举
隐式地扩展 java.lang.Enum
),但是为了仅添加额外的方法,而不是额外的枚举值,一个扩展
一个枚举
的类。 p>
如下所示:
枚举MyEnum
{
ASD(5),
QWE(3),
ZXC(7);
private int number;
private asd(int number)
{
this.number = number;
}
public int myMethod()
{
return this.number;
}
}
class MyClass extends MyEnum
{
public int anotherMethod()
{
return this.myMethod )1;
}
}
使用如下:
System.out.println(MyClass.ASD.anotherMethod());
所以,任何人都可以为此限制提供理由(或指向正确的JLS部分)?
我认为他们为什么这样做的答案来自于这个问题: p>
在你的例子中,你将如何实例化一个MyClass?枚举从未被用户明确实例化(通过新的MyEnum()
)。您必须执行类似 MyClass.ASD
的操作,但不知道该如何工作。
基本上,我不知道什么语法将适用于您的建议添加。这可能是为什么他们使他们成为最终等...
编辑添加
如果原作者Enum计划在前进(不太可能),你不用担心线程的安全,你可以这样做:(BTW,我可能会尖叫任何人谁实际上这样做在生产代码,YMMV)
public enum ExtendibleEnum {
FOO,BAR,ZXC;
private Runnable anotherMethodRunme; //确切的接口会有所不同,我选择了一个简单的一个
//这是你的其他类$
$ b public void setAnotherMethodRunMe(Runnable r){//在这里注入
anotherMethodRunme = r;
}
public void anotherMethod(){//这个行为被改变
anotherMethodRunme.run();
}
}
I am wondering why in the Java language a class
cannot extend an enum
.
I'm not talking about an enum
extending an enum
(which can't be done, since java doesn't have multiple inheritance, and that enum
s implicitly extend java.lang.Enum
), but a class that extends
an enum
in order to only add extra methods, not extra enumeration values.
Something like:
enum MyEnum
{
ASD(5),
QWE(3),
ZXC(7);
private int number;
private asd(int number)
{
this.number=number;
}
public int myMethod()
{
return this.number;
}
}
class MyClass extends MyEnum
{
public int anotherMethod()
{
return this.myMethod()+1;
}
}
To be used like this:
System.out.println(MyClass.ASD.anotherMethod());
So, can anyone provide a rationale (or point me to the right JLS section) for this limitation?
I think an answer to why they did it this way comes from this question:
In your example, how would you instantiate a MyClass? Enums are never explicitly instantiated (via a new MyEnum()
) by the user. You'd have to do something like MyClass.ASD
but not sure how that would work.
Basically, I don't know what syntax would work for your proposed addition. Which is probably why they made them final etc...
EDIT ADDED
If the author of the original Enum planned ahead (unlikely), and you are not worried too much abut thread safety, you could do something like this: (BTW, I'd probably scream at anybody who actually did this in production code, YMMV)
public enum ExtendibleEnum {
FOO, BAR, ZXC;
private Runnable anotherMethodRunme; // exact Interface will vary, I picked an easy one
// this is what gets "injected" by your other class
public void setAnotherMethodRunMe(Runnable r) { // inject here
anotherMethodRunme= r;
}
public void anotherMethod() { // and this behavior gets changed
anotherMethodRunme.run();
}
}
这篇关于为什么一个类不能扩展枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!