From the SCJP Questions PDF book, I got this question..
1. enum Animals {
2. DOG("woof"), CAT("meow"), FISH("burble");
3. String sound;
4. Animals(String s) { sound = s; }
5. }
6. class TestEnum {
7. static Animals a;
8. public static void main(String[] args) {
9. System.out.println(a.DOG.sound + " " + a.FISH.sound);
10. }
11. }
The Options are,
A. woof burble
B. Multiple compilation errors
C. Compilation fails due to an error on line 2
D. Compilation fails due to an error on line 3
E. Compilation fails due to an error on line 4
F. Compilation fails due to an error on line 9
A is the correct Answer,..
Can some body explain this..
Whether the enum can have constructors?
Yes, enums can have constructors and methods and instance variables just like other classes. But you cannot call the constructor yourself, like you would with a regular class. You can't call a= new Dog("wooooof"). The constructor will be called by the compiler for you.
This will compile fine, but on line 9, I think the compiler will warn you that you are accesing a static field in a a non-static way. Animal.DOG.sound is the "proper way" and not a.DOG.sound.