• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Enum reference confusion

 
Matthew Alesi
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm currently reading K&B's SCJP 5.0 book, and I have a small doubt about Chapter 1, Self-test question number 8. It gives the following code:

enum Animals {
DOG("woof"), CAT("meow"), FISH("burble");
String sound;
Animals(String s) { sound = s; }
}
class TestEnum {
static Animals a;
public static void main(String[] args) {
System.out.println(a.DOG.sound + " " + a.FISH.sound);
}
}

The question essentially asks whether it compiles or not, and I said no because of the way the "sounds" are referenced. The variable a is never initialized, but is used to access the enum values. Is it always okay to access static members through a reference variable that was never initialized? Thanks!

-Matt
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the case of an enum, you can't initialize it yourself. You can't call the constructor of an enum. The enum is implicitly static, and when initialized, the constructor is automatically called for each entry in the enum.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my opinion TestEnum would have been better presented as below rather than using (or misusing) a static variable.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic