是否可以扩展 Java 枚举? [英] Is it possible to extend Java Enums?

查看:23
本文介绍了是否可以扩展 Java 枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要完成的事情,我有一个包含一些值的枚举的类,我想对其进行子类化并向枚举添加更多值.这是一个不好的例子,但是:

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 枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆