File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Enum Variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Enum Variables" Watch "Enum Variables" New topic

Enum Variables

Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62

Variable points is private to Days. How am I able to print it in main?

Thanks for your help in advance.

Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

It's not that you are "printing it in main". It's that you are accessing it from the Enums class. That variable is a member of the Enums class and therefore any code in the Enums class has access to it.
Bert Wilkinson
Ranch Hand

Joined: Oct 28, 2009
Posts: 33
More clearly,

You have defined a Class called "Days" that has a private instance variable. So, you need to have a method to retrieve the information you want....

take a look at the java tutorial on has a very relevant example. You need a "getter" method in your enum class
Rob Spoor

Joined: Oct 27, 2005
Posts: 20279

Paul is right. Access modifiers like private limit access to classes, not instances of those classes.

How To Ask Questions How To Answer Questions
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
I think the more relevant point, in this case, is that a private field is private to whatever top-level class it's contained within. If it's declared in a nested class ("Days" in this case), that private field is still accessible outside the nested class, but inside the containing top-level class ("Enums" in this case).

Why did Java do it this way? I don't know. It's been this way since nested classes were introduced, I think. Well, at least since JLS second edition. Nested classes had a lot of ambiguities before that.

By coincidence, we had a closely related discussion in my Scala reading group at work today. One of the differences between Scala and Java access specifiers is that in Scala, private means private to whatever class immediately contains the thing you're declaring as private. Scala's creator evidently thought this was more logical - you're scoped to the closest set of matching containing braces. But then Scala also lets your specify more esoteric options, like private[this] or private[OtherClassName] or private[]. So I think Scala gives a more logically consistent default, while also letting you do other things if you think you need to. Meanwhile in Java, many people still don't realize that private variables can be accessed in other classes, as long as you're still in the same top-level class. It's one of those Java gotchas that occasionally bites people.
I agree. Here's the link:
subject: Enum Variables
It's not a secret anymore!