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?
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
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”.
Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.
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.
All code inside single outer class can access anything in that outer class whatever access level is.
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.
First check out line 12
System.out.println(Suits.NOTRUMP.getBidValue(3));
getBidValue is undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With