是否可以扩展Java Enums? [英] Is it possible to extend Java Enums?
本文介绍了是否可以扩展Java Enums?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我要完成的工作,我有一个类包含一些值的枚举,我想将其子类化,并向枚举中添加更多的值。这是一个不好的例子,但是:
Here's what I am looking to accomplish, I have a class that has an enum of some values and I want to subclass that and add more values to the enum. This is a bad example, but:
public class Digits
{
public enum Digit
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
}
}
public class HexDigits extends Digits
{
public enum Digit
{
A, B, C, D, E, F
}
}
,以便HexDigits.Digit包含所有十六进制数字。这是可能的吗?
so that HexDigits.Digit contains all Hex Digits. Is that possible?
推荐答案
不可以。最好的做法是使两个枚举实现和接口,然后使用该接口而不是枚举。所以:
No it's not possible. The best you can do is make two enums implement and interface and then use that interface instead of the enum. So:
interface Digit {
int getValue();
}
enum Decimal implements Digit {
ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE;
private final int value;
Decimal() {
value = ordinal();
}
@Override
public int getValue() {
return value;
}
}
enum Hex implements Digit {
A, B, C, D, E, F;
private final int value;
Hex() {
value = 10 + ordinal();
}
@Override
public int getValue() {
return value;
}
}
这篇关于是否可以扩展Java Enums?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文