Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Enum member variable access

 
Mary John
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Output of above code gives
red
false


why is it giving red? shouldnt it be a compiler error or if not give some exception. please explain..

thanks in advance
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The member variable 'name' in the enum doesn't have an access specifier (public, protected, private), so it has default access - which means that other classes in the same package such as class Class can access it.

See The Java Tutorial - Controlling Access to Members of a Class

Note that an enum is a kind of special class, and the access rules for classes apply to enums as well.
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, also the statement:
Color a = Color.Green;
Here 'a' is reference variable of type 'Color' that refers to an enum type 'Green'. You can use it more less you use a reference variable. The statement:
System.out.println(a.Red.name);
Its ok to access another enum type using the same variable, even you can use it to refer to another enum type: a = Color.Blue;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic