关于java中类内部定义的枚举的问题
这段代码取自 SCJP 实践测试:
3. public class Bridge {
4. public enum Suits {
5. CLUBS(20), DIAMONDS(20), HEARTS(30), SPADES(30),
6. NOTRUMP(40) { public int getValue(int bid) {
return ((bid-1)*30)+40; } };
7. Suits(int points) { this.points = points; }
8. private int points;
9. public int getValue(int bid) { return points * bid; }
10. }
11. public static void main(String[] args) {
12. System.out.println(Suits.NOTRUMP.getBidValue(3));
13. System.out.println(Suits.SPADES + " " + Suits.SPADES.points);
14. System.out.println(Suits.values());
15. }
16. }
第 8 行 points
被声明为私有,第 13 行它正在被访问,所以从我可以看到我的答案是编译失败。 但书中的答案却另有说法。 我在这里遗漏了什么还是书中的错字?
This code is taken from a SCJP practice test:
3. public class Bridge {
4. public enum Suits {
5. CLUBS(20), DIAMONDS(20), HEARTS(30), SPADES(30),
6. NOTRUMP(40) { public int getValue(int bid) {
return ((bid-1)*30)+40; } };
7. Suits(int points) { this.points = points; }
8. private int points;
9. public int getValue(int bid) { return points * bid; }
10. }
11. public static void main(String[] args) {
12. System.out.println(Suits.NOTRUMP.getBidValue(3));
13. System.out.println(Suits.SPADES + " " + Suits.SPADES.points);
14. System.out.println(Suits.values());
15. }
16. }
On line 8 points
is declared as private, and on line 13 it's being accessed, so from what I can see my answer would be that compilation fails. But the answer in the book says otherwise. Am I missing something here or is it a typo in the book?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
单个外部类中的所有代码都可以访问该外部类中的任何内容,无论访问级别是什么。
All code inside single outer class can access anything in that outer class whatever access level is.
扩展stepancheg所说的:
来自Java语言规范第 6.6.1 节“确定可访问性”:
本质上,
private
并不意味着这个类私有,它意味着顶级类私有。To expand on what stepancheg said:
From the Java Language Specification section 6.6.1 "Determining Accessibility":
Essentially,
private
doesn't mean private to this class, it means private to the top-level class.首先检查第12行
getBidValue是否未定义
First check out line 12
getBidValue is undefined
同样,内部类可以访问其外部类的私有成员。
Similarly, an inner class can access to private members of its outer class.