扩展和枚举不变

时间:2012-05-29 13:17:44

标签: java enums

是否可以让一个枚举常量扩展另一个(来自相同的枚举)?

的伪代码:

private enum Mode{
  FRIGHTENED, BLINKING extends FRIGHTENED, SCATTER
}

这样,人们就可以在switch - 块中使用枚举常量,如下所示:

switch (some_mode){
  case FRIGHTENED:
    // This would trigger when the actual "some_mode" is set
    //  to FRIGHTENED or BLINKING
    break;
  case BLINKING:
    // This would only trigger if the actual "some_mode" is set to BLINKING
}

是否有任何模式可以让我这样做,或者我完全不在我的脑海里?


我可能需要对switch语句中显示的用例更清楚一点:我打算不检查所有可能的值,但仅针对“父”值。

if (some_mode == Mode.FRIGHTENED){
  // The behavior in FRIGHTENED and BLINKING mode is the same. The only
  //  difference is the way they are visualized.
}

3 个答案:

答案 0 :(得分:1)

在Java中,无法扩展枚举,因此如果要整理与强烈相关的枚举,可以使用嵌套枚举构造。请查看this thread

答案 1 :(得分:0)

不,没有办法做到这一点。最接近的选择是

switch (some_mode){
  case BLINKING:
    // This would only trigger if the actual "some_mode" is set to BLINKING
    // no break statement!
  case FRIGHTENED:
    // This would trigger when the actual "some_mode" is set
    //  to FRIGHTENED or BLINKING
}

答案 2 :(得分:0)

有一种折磨方式来模拟这个,但不是,一个枚举常数不可能扩展另一个。