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.
類似地,內部類可以訪問其外部類的私有成員。