有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

关于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行它被访问,所以从我看到的答案是编译失败。但书中的答案是相反的。我是遗漏了什么还是书中有错


共 (4) 个答案

  1. # 1 楼答案

    无论访问级别如何,单个外部类中的所有代码都可以访问该外部类中的任何内容

  2. # 2 楼答案

    进一步阐述stepancheg所说的:

    Java Language Specification section 6.6.1 "Determining Accessibility"开始:

    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并不意味着对这个类私有,它意味着对顶级类私有

  3. # 3 楼答案

    先退房第12行

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

    getBidValue未定义

  4. # 4 楼答案

    类似地,内部类可以访问其外部类的私有成员