aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static member access in enum Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static member access in enum" Watch "Static member access in enum" New topic
Author

Static member access in enum

Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
Hi! Why Test1 compiles, but Test2 doesn't compile. I expected both don't compile because it is illegal to access static member from enum constructor or instance initializer.

enum Test1 {
FIRST, SECOND;
private static int test = 1;

private int i = test; // Compilation ok
}

enum Test2 {
FIRST, SECOND;
private static int test = 1;

{
System.out.println(test); // Compilation fails
}
}


Java is my love
Mark Uppeteer
Ranch Hand

Joined: Mar 02, 2004
Posts: 159

you cannot access non static data from a static context.
an initializer isn't static, unless it is a static initilaizer.
this works:


[ November 15, 2007: Message edited by: Mark Uppeteer ]

I know where my towel is. (SCJP 5, OCPJWCD)
[Free Quiz Tips for a fun night with friends or family] Flash games
Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
Mark, I agree with you. But what about first example? It is not static initializer! And it compiles fine.
Mark Uppeteer
Ranch Hand

Joined: Mar 02, 2004
Posts: 159

Sorry, I was wrong. Of course you can access static vars from non static context. It's the other way around that does not work! (call a non static method from a in a static one for example).

This does work with regular classes. Its only with the enum that it doesn't work.
Interesting, I don't know the explanation.
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
This is from JLS:

It is a compile-time error to reference a static field of an enum type that is not a compile-time constant (�15.28) from constructors, instance initializer blocks, or instance variable initializer expressions of that type.

In your example you need to add 'final' to the static variable declaration to make it a compile- time constant and hence be able to use it in an init block.
Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
Ahmed Yehia, you are right, but in Test1 class 'test' is not final, and this class compiles without errors anyway. Why? I don't know answer.
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
'Test1' doesn't compile for the same reason, same rule apply.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static member access in enum