Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum Types as explained in Effective Java by Joshua Bloch

Please see this link. Regarding Enums, Mr. Bloch says

Java’s enum types are classes that export one instance for each enumeration constant via a public static final field.

I read the Enum Class documentation but there was no public static final field, then how does the above statement hold true. Please explain. Thanks

like image 762
Ankit Avatar asked May 05 '15 07:05

Ankit


2 Answers

Create a Test.java file and write Test enum:

public enum Test {
    Hello
}

compile this class: javac Test.java,and use javap Test to get the compiled class:

public final class Test extends java.lang.Enum{
    public static final Test Hello;
    public static Test[] values();
    public static Test valueOf(java.lang.String);
    static {};
}

and you can see the Test class extends from Enum and it has the public static final Hello field.

like image 135
chengpohi Avatar answered Sep 19 '22 10:09

chengpohi


Enum is the base class for all enums. It doesn't contain constants. What contains constants are the concrete enum classes themselves. See for example the documentation for the enum Locale.Category. It does contain public static final fields for each enum constant: DISPLAY and FORMAT.

like image 41
JB Nizet Avatar answered Sep 21 '22 10:09

JB Nizet