Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A question about enums defined inside a class in java

Tags:

java

enums

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?

like image 273
Vasil Avatar asked May 04 '09 05:05

Vasil


People also ask

Can we have enum inside a class in Java?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

Can we define enum inside a method in Java?

We can an enumeration inside a class. But, we cannot define an enum inside a method. If you try to do so it generates a compile time error saying “enum types must not be local”.

Can we create the enum inside and outside of the class?

Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.

In which cases should we consider using enums in Java?

When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.


3 Answers

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

like image 189
stepancheg Avatar answered Nov 14 '22 21:11

stepancheg


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.

like image 30
newacct Avatar answered Nov 14 '22 20:11

newacct


First check out line 12

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

getBidValue is undefined

like image 36
Cesar Avatar answered Nov 14 '22 22:11

Cesar