Enum Types as explained in Effective Java by Joshua Bloch

北慕城南 提交于 2019-12-21 15:08:25

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/30046344/enum-types-as-explained-in-effective-java-by-joshua-bloch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!