Java常量特定类体私有变量访问

时间:2018-02-14 17:07:31

标签: java enums static

为什么这不能编译,并且(相关地)为什么CC无法访问我想到的(也许我错了)它自己的(私有)成员变量i,当AA和BB确实可以所以? CC如何访问自己的成员变量?

谢谢。

enum TestEnum {
  AA(1000), BB(500), CC(100) {
    public int getI() {
      return i + 1;
    }
  };
  TestEnum(int i) {
    this.i = i;
  }

  private int i;
  public int getI() {
    return this.i;
  }
}

javac输出:

TestEnum.java:6: error: non-static variable i cannot be referenced from a static context
                 public int getI() { return i + 1; }
                                            ^
1 error

2 个答案:

答案 0 :(得分:2)

使用super.getI() - 1,因为您要覆盖父方法。

public enum TestEnum {
    AA(1000), BB(500), CC(100) {

        @Override
        public int getI() {
            return super.getI() - 1;
        }
    };

    private int i;

    TestEnum(int i) {
        this.i = i;
    }

    public int getI() {
        return this.i;
    }
}

或者让字段protected直接访问它(return i - 1;),正如@oleg cherednik建议的那样。但是,我更喜欢上面的解决方案。

答案 1 :(得分:1)

您有两种选择:执行protected字段或致电super.getId()我更喜欢先做一个,更容易阅读注意:考虑枚举体parent class和每个常量,例如children,因此您的私人字段在children AA, BB, CC中不可见。

public enum TestEnum {
    AA(1000),
    BB(500),
    CC(100) {
        @Override
        public int getI() {
            return i + 1;
        }
    };

    protected final int i;

    TestEnum(int i) {
        this.i = i;
    }

    public int getI() {
        return i;
    }
}

P.S。最好在枚举中只有final个字段,因为枚举就像常量一样,不应该有任何变量。