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

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

    When an identifier is resolved, Java prefers the lexical scope over inherited members. So when you have an inner class that extends the outer class and use a field of the outer class without using this or super, the field of the outer instance is accessed which fails if the inner class is static as there is no outer instance then. In contrast, when using super you are explicitly accessing the inherited member. Note that enum classes are implicitly static. You can even use this to access the inherited member but you have to use ((MyClass)this).someField to access it if it’s declared private.

提交回复
热议问题