Why can enum implementations not access private fields in the enum class

后端 未结 4 951
陌清茗
陌清茗 2020-12-15 16:59

I just answered this question by saying how to solve the compilation problem:

How to use fields in java enum by overriding the method?

But what I don\'t unde

4条回答
  •  悲&欢浪女
    2020-12-15 17:17

    I disagree with the accepted answer.

    The enum const declaration is implicit public static final, but not the class the enum const belongs to.

    From JSL Chapter 8.Classes

    The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type. The class body is governed by the usual rules of anonymous classes.

    And what the 'rules of anonmous classes'?

    From JSL Chapter 15:

    An anonymous class declaration is automatically derived from a class instance creation expression by the Java compiler.

    An anonymous class is never abstract (§8.1.1.1).

    An anonymous class is always implicitly final (§8.1.1.2).

    An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1).

    And if the enum equivalent class is a static class, how to explain the following error?

    public enum MyClass {
        First {
            public static int b;  //(2)Illegal static declaration in inner class
        };
    }
    

    But why a inner class can't access the outer class's field?

    A possible enum equivalent class may looks like following, which gives the same error as a enum class:

    abstract class MyClass {    
        private int someField;
        static {
            class First extends MyClass {
                public void method() {
                    System.out.println(someField);
                }
                private static int b;
            }
        }
    }
    

    More:

    • Nested enum is static?
    • How is enum implemented?

提交回复
热议问题