This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static member access in enum

 
Andry Dub
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
}
}
 
Mark Uppeteer
Ranch Hand
Posts: 159
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Andry Dub
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mark, I agree with you. But what about first example? It is not static initializer! And it compiles fine.
 
Mark Uppeteer
Ranch Hand
Posts: 159
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'Test1' doesn't compile for the same reason, same rule apply.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic