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

后端 未结 4 939
陌清茗
陌清茗 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:26

    Your abstract class is not equivalent to your enum, since enums are implicitly public static final. Thus, you'll observe the same behavior if you use:

    abstract class MyClass {
    
        static class FIRST extends MyClass {
    
            @Override
            public String doIt() {
                return "1: " + someField; // error
            }
    
        };
    
        static class SECOND extends MyClass {
    
            @Override
            public String doIt() {
                return "2: " + super.someField; // no error
            }
    
        };
    
        private String someField;
    
        public abstract String doIt();
    
    }
    

    As explained in http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html, chapter "Static Nested Classes":

    A static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.

    Thus the need of super. You could also use this if the field were protected rather than private.

提交回复
热议问题