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

can't access to a private instance field from an enum method

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P5 P5
    • None
    • 6
    • tools
    • x86
    • windows_xp

      FULL PRODUCT VERSION :
      java version "1.6.0-ea"
      Java(TM) 2 Runtime Environment, Standard Edition (build 1.6.0-ea-b54)
      Java HotSpot(TM) Client VM (build 1.6.0-ea-b54, mixed mode, sharing)

      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows XP [version 5.1.2600]

      A DESCRIPTION OF THE PROBLEM :
      It's impossible to access to a private instance variable from a
      method or from an initialisation bloc.
      The compiler doen't generate acessor like in inner/anonymous classes.

      The JLS3 says that
      "class body is governed by the usual rule of anonymous classes".
      page 255, capter 8.9.

      Futhermore, the error message is weird :
      "non-static variable val cannot be referenced from a static context"
      and not something like "inacessible variable".


      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      compile the following code

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      it must compile
      ACTUAL -
      it doen't compile

      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      javac -d ../classes EnumInitBlock.java
      EnumInitBlock.java:5: non-static variable val cannot be referenced from a static
       context
           val=3;
           ^
      EnumInitBlock.java:8: non-static variable val cannot be referenced from a static
       context
           return Integer.toString(val);
                                   ^
      2 errors

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      public enum EnumInitBlock {
        max {
         {
           val=3;
         }
         @Override public String toString() {
           return Integer.toString(val);
         }
        };
        {
          val=2;
        }
        private int val;
        public static void main(String[] args) {
          System.out.println(max); // 3
        }
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      declare val as package visible.

            ahe Peter Ahe
            ndcosta Nelson Dcosta (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: