java enum in class_關於在java中的類中定義的枚舉的問題

This code is taken from a SCJP practice test:

此代碼取自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. }

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?

在線8點被聲明為私有,在第13行它被訪問,所以從我可以看到我的答案將是編譯失敗。但書中的答案卻另有說法。我在這里遺漏了什么,還是書中的拼寫錯誤?

4 个解决方案

#1

All code inside single outer class can access anything in that outer class whatever access level is.

單個外部類中的所有代碼都可以訪問該外部類中的任何訪問級別。

#2

To expand on what stepancheg said:

為了擴展stepancheg說的話:

從Java語言規范部分6.6.1“確定可訪問性”:

if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class that encloses the declaration of the member or constructor.

如果成員或構造函數被聲明為private,則當且僅當它發生在包含成員或構造函數聲明的頂級類的主體內時才允許訪問。

Essentially, private doesn't mean private to this class, it means private to the top-level class.

從本質上講,私有並不意味着私有這個類,它意味着私有的頂級類。

#3

First check out line 12

首先檢查第12行

System.out.println(Suits.NOTRUMP.getBidValue(3));

getBidValue is undefined

getBidValue未定義

#4

Similarly, an inner class can access to private members of its outer class.

類似地,內部類可以訪問其外部類的私有成員。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值