reading the SCJP book, I’ve found something like this in the chapter 1 “self-test” :
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 following line is from me
System.out.println(Animals.DOG.sound + " " + Animals.FISH.sound);
}
}
Note: the code compile fine.
What I don’t understand is why we can access the DOG, CAT or FISH constants from the variable a. I thought (and it is also written in the book) that the DOG, FISH, CAT being constants are implemented in a way similar to public static final Animals DOG = new Animals(1);
So if they really are static why can we access them from a ?
The last line is the way I am familiar with.
Writing
a.DOGis the same as writingAnimal.DOG. That is, the compiler will replace the variable with its compile time type Animal. It is considered bad code since it hides the fact that it relies on the compile time type instead of the dynamic type ofa.