Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-7119746

Nested enum class cannot access a private field of its enum.

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 7
    • tools
    • x86
    • linux

      FULL PRODUCT VERSION :
      java version "1.7.0_01"
      Java(TM) SE Runtime Environment (build 1.7.0_01-b08)
      Java HotSpot(TM) 64-Bit Server VM (build 21.1-b02, mixed mode)


      A DESCRIPTION OF THE PROBLEM :
      When a nested enum class tries to access the outer, it gets an error message about being unable to access a non-static field in a static context. However making the field package local, or using the super keyword "fixes" the problem, which is not obvious from the error message.

      If the enum were a nested class, it would have no trio

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Compile the code below.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The error message doesn't make it clear that using the super. keyword would "fix" the problem. It doesn't appear to be correct behaviour, but if it is the error message gives no indication as to the solution.
      ACTUAL -
      The same behaviour as the following.

      public class MyNotEnum {
          public class NestedNotEnum extends MyNotEnum {
              public int getMemberVariableFailes() {
                  // compiles just fine.
                  return memberVariable;
              }

              public int getMemberVariableOK() {
                  return super.memberVariable;
              }
          }
          private final int memberVariable = 1;
      }


      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      error: non-static variable memberVariable cannot be referenced from a static context

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      public enum MyEnum {
          One {
              public int getMemberVariableFailes() {
                  // error: non-static variable memberVariable cannot be referenced from a static context
                  return memberVariable;
              }

              public int getMemberVariableOK() {
                  return super.memberVariable;
              }

              public int getMemberVariable2OK() {
                  return memberVariable2;
              }
          };

          private final int memberVariable = 1;
          final int memberVariable2 = 1;
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Use the super keyword to access the field.

      SUPPORT :
      YES

            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: