【发布时间】:2015-10-22 16:11:44
【问题描述】:
最近我遇到了以下一段代码:
enum Animals {
DOG("woof"), CAT("meow"), FISH("burble");
String sound;
Animals(String s) {
sound = s;
}
}
class TestEnum {
static Animals a;
public static void main(String[] args) {
System.out.println(a.DOG.sound + " " + a.FISH.sound);//Expected compilation failure
}
}
我希望代码因为这个a.DOG.sound 部分而无法编译。但令我惊讶的是,事实并非如此。我四处搜索,包括official documentation 以找出访问级别,但一无所获。是 public 还是 default?
【问题讨论】:
-
适用正常的可访问性访问规则。
-
好问题。在这种情况下,
String sound缺少访问修饰符,这使其具有默认可见性。这意味着它对同一包中的所有其他类都是可见的。查看this chart,特别是int i行。