aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Enum reference confusion 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 "Enum reference confusion" Watch "Enum reference confusion" New topic
Author

Enum reference confusion

Matthew Alesi
Ranch Hand

Joined: Sep 13, 2006
Posts: 38
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


-Matt
Current CS undergrad
SCJP 5.0
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Aug 03, 2002
Posts: 7729
In my opinion TestEnum would have been better presented as below rather than using (or misusing) a static variable.



Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Enum reference confusion