Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: access to the constants in an enumeration (enum)

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.

like image 813
grandouassou Avatar asked Mar 05 '11 20:03

grandouassou


1 Answers

Although this works, don't do it like that. Use enums with Animal.DOG, Animal.CAT, etc.

What the above does is declare an object of the enum type, and reference the static DOG on it. The compiler knows the type of a, and knows that you want Animal.DOG. But this kills readability.

I believe the purpose of this is to shorten the usage of enums. a.DOG instead of Animal.DOG. If you really want to shorten it, you can use import static fqn.of.Animal and then use simply DOG.

like image 78
Bozho Avatar answered Oct 19 '22 00:10

Bozho