Vasil
Vasil

Reputation: 38126

A question about enums defined inside a class in java

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?

Upvotes: 6

Views: 5854

Answers (4)

aows
aows

Reputation: 526

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

Upvotes: 0

newacct
newacct

Reputation: 122489

To expand on what stepancheg said:

From the 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.

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

Upvotes: 5

stepancheg
stepancheg

Reputation: 4276

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

Upvotes: 11

Cesar
Cesar

Reputation: 1610

First check out line 12

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

getBidValue is undefined

Upvotes: 3

Related Questions