java枚举编译后_java – 为什么这个枚举编译?

It is a compile-time error for the constructors, instance initializer blocks, or instance variable initializer expressions of an enum constant e to refer to e or to an enum constant of the same type that is declared to the right of e.

这里的规范只是意味着您不能以名称引用,因为e所引用的字段尚未初始化.这并不意味着你无法访问这个.

它基本上与任何其他初始化器(如int x = x;)相同.

我们可以看到为什么像(Ideone)这样的例子:

enum Example {

INSTANCE {{

subversion();

}};

static void subversion() {

System.out.println(INSTANCE);

}

public static void main(String[] args) {

System.out.println(INSTANCE);

}

}

哪个输出

null

INSTANCE

I found that if mMap is private, it cannot be referenced in the instance initializer.

您可以将呼叫限定为super.mMap.put(…);.私有的mMap不是继承的,但是它可以从内部类中访问. I also covered this here.简而言之,简单的名称mMap是指一个不存在的Derp的外部实例.

我们可以用(Ideone)这样的例子来证实这一点:

class Example {

private int x;

class Inner extends Example {{

x = 1; // refers to the outer instance

super.x = 2; // refers to the inner instance

}}

public static void main(String[] args) {

Example outer = new Example();

Example inner = outer.new Inner();

System.out.println(outer.x); // prints 1

System.out.println(inner.x); // prints 2

}

}

除了你的情况,FOO是静态的,所以没有外部实例,因此编译错误.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值