17

Consider the following code:

enum E {
    A { public int get() { return i; } },
    B { public int get() { return this.i; } },
    C { public int get() { return super.i; } },
    D { public int get() { return D.i; } };

    private int i = 0;
    E() { this.i = 1; }
    public abstract int get();
}

I get compile-time errors on the first 2 enum constants declarations (A & B) but the last 2 compile fine (C & D). The errors are:

Error 1 on line A: non-static variable i cannot be referenced from a static context
Error 2 on line B: i has private access in E

Since get is an instance method, I don't understand why I can't access the instance variable i the way I want.

Note: removing the private keyword from the declaration of i also makes the code compilable, which I don't understand either.

Using Oracle JDK 7u9.

EDIT

As pointed out in the comments, this is not specific to enums and the code below produces the same behaviour:

class E {
    static E a = new E() { public int get() { return i; } };
    static E b = new E() { public int get() { return this.i; } };
    static E c = new E() { public int get() { return super.i; } };
    static E d = new E() { public int get() { return d.i; } };

    private int i = 0;
}
assylias
  • 321,522
  • 82
  • 660
  • 783
  • 1
    Same question here. After a long time, I still lie to myself that *I know enums in java* :) – mtk Jan 03 '13 at 12:19
  • 2
    For more fun, try `return this.i;` instead of `A.i`. – Marko Topolnik Jan 03 '13 at 12:22
  • 1
    @MarkoTopolnik `return this.i;` and `return i;` do not compile but `return super.i;` and `return A.i;` do. – assylias Jan 03 '13 at 12:25
  • 4
    Exactly, and each of them fails with a different error! That's the "more fun" part :) – Marko Topolnik Jan 03 '13 at 12:27
  • assylias, do note that your error is not enum-specific. Try code from Evgeniy's answer, it produces the exact same compiler errors with a regular class. – Marko Topolnik Jan 03 '13 at 13:07
  • About why it works when removing `private`, I think that one can be explained adequately. There is a certain search order to resolve `i` and looking it up as a static variable is the last option. This step finds `i`, concludes it can't be accessed, but attributes the reason for that to the wrong cause. This is a glitch in error reporting, the underlying cause still being improper implementation of access rules. – Marko Topolnik Jan 03 '13 at 13:19

4 Answers4

6

The observed behavior is mandated by the Java Language Specification, in particular implicit access to fields of enclosing types, and the rule that private members are not inherited.

unqualified field access

A { public int get() { return i; } }

The spec mandates:

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; in particular it cannot contain any constructors.

This makes the expression i somewhat ambiguous: Are we referring to the field of the enclosing instance, or the inner instance? Alas, the inner instance doesn't inherit the field:

Members of a class that are declared private are not inherited by subclasses of that class.

Therefore, the compiler concludes we mean to access the field of the enclosing instance - but being in a static block, there is no enclosing instance, hence the error.

field access through this

B { public int get() { return this.i; } },

The spec mandates:

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.

Therefore, it is quite clear we want the field of the inner class, not the outer one.

The reason the compiler rejects the field access expression this.i is:

Members of a class that are declared private are not inherited by subclasses of that class.

That is, a private field can only be accessed through a reference of the type that declares the field, not a subtype thereof. Indeed,

B { public int get() { return ((E)this).i; } },

compiles just fine.

access through super

Like this, super refers to the object the method was invoked on (or the object being constructed). It is therefore clear we mean the inner instance.

Additionally, super is of type E, and the declaration therefore visible.

access through other field

D { public int get() { return D.i; } };

Here, D is an unqualified access to the static field D declared in E. As it is a static field, the question of which instance to use is moot, and the access valid.

It is however quite brittle, as the field is only assigned once the enum object is fully constructed. Should somebody invoke get() during construction, a NullPointerException would be thrown.

Recommendation

As we have seen, accessing private fields of other types is subject to somewhat complex restrictions. As it is rarely needed, developers may be unaware of these subtleties.

While making the field protected would weaken access control (i.e. permit other classes in the package to access the field), it would avoid these issues.

meriton
  • 68,356
  • 14
  • 108
  • 175
  • I mostly agree, except *"being in a static block, there is no enclosing instance, hence the error"* => get is an instance method. The variable assignement occurs in a static context (A = new E() {...}) but the statement `return i;` does not. – assylias Jan 03 '13 at 17:43
  • 1
    @assylias I think meriton's logic is impeccable: there really is no enclosing instance and the statement `return i` occurs in the context of an instance that didn't inherit `i`. – Marko Topolnik Jan 03 '13 at 17:52
  • @assylias: Did Marko answer your question or should I elaborate more on a particular aspect? – meriton Jan 03 '13 at 19:37
  • @meriton I think I need to re-read everything calmly tomorrow morning but it seems that your answer is the right one. – assylias Jan 03 '13 at 20:15
  • 1
    @assylias The combination of the rule that private members are not inherited and the fact that the anonymous class has no enclosing instance explains everything. I overlooked the first of those two facts when writing my answer. – Marko Topolnik Jan 03 '13 at 20:30
3

Take a look at this piece of code:

public class E 
{
  final int i;
  private final int j;
  final E a;

  E() { i = j = 0; a = null; }

  E(int p_i) {
    this.i = this.j = p_i;
    a = new E() {
      int getI() { return i; }
      int getJ() { return j; }
    };
  }

  int getI() { throw new UnsupportedOperationException(); }
  int getJ() { throw new UnsupportedOperationException(); }

  public static void main(String[] args) {
    final E ea = new E(1).a;
    System.out.println(ea.getI());
    System.out.println(ea.getJ());
  }
}

this prints

0
1

and the only difference between i and j is the access level!

This is surprising, but it is correct behavior.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

Update

It does appear that it is because it is defined in a static block. Take a look at the following:

    private E works = new E("A", 0) {

        public int get() {
            return i; // Compiles
        }
    };

    static {
        A = new E("A", 0) {

            public int get() {
                return i; // Doesn't Compile
            }

        };
    }

Original

I compiled the enum and then decompiled it using Jad to see what the code might look like:

static abstract class E extends Enum
{

    public static E[] values()
    {
        return (E[])$VALUES.clone();
    }

    public static E valueOf(String s)
    {
        return (E)Enum.valueOf(Foo$E, s);
    }

    public abstract int get();

    public static final E A;
    private int i;
    private static final E $VALUES[];

    static
    {
        A = new E("A", 0) {

            public int get()
            {
                return A.i;
            }

        }
;
        $VALUES = (new E[] {
            A
        });
    }


    private E(String s, int j)
    {
        super(s, j);
        i = 0;
        i = 1;
    }

}

This makes it clearer to me that A is an anonymous inner class defined in a static init block of type E. Looking around for private member visibility in anonymous inner classes, I found the following in this answer ( Why are only final variables accessible in anonymous class? ):

When you create an instance of an anonymous inner class, any variables which are used within that class have their values copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does

From this I take it that A.i refers to this copied variable in A, and not i declared in E. The only way to get the i in E is if it is either static or not private.


Community
  • 1
  • 1
John Farrelly
  • 7,289
  • 9
  • 42
  • 52
  • 1) We all know it is an anonymous inner class. 2) In your quote, "variables" implies "local variables" and doesn't apply here. – Marko Topolnik Jan 03 '13 at 13:20
  • @MarkoTopolnik On (1) I missed a bit of typing. My surprise was that it's an anonymous inner class defined in a static block. This is what makes me think that A has no access to the private instance variables of E. – John Farrelly Jan 03 '13 at 13:37
  • To be precise, it is not an anonymous **inner**, but **nested** class (it has no enclosing instance), and this is why your `works` in the example compiles: it invokes different access rules, those for the fields of the enclosing instance. This doesn't explain the **reason** why OP's code produces a compiler error. – Marko Topolnik Jan 03 '13 at 13:58
  • @JohnFarrelly Note that in my second example there is no static block. – assylias Jan 03 '13 at 14:11
  • @assylias In your second example, all the variables are declared as static, so would have the similar issue. If you make them non-static they all compile. – John Farrelly Jan 03 '13 at 14:19
0

private methods can be accessed in nested classes provided that are in the same class file.

For this reason, the first example works even though A is an anonymous sub-class of E. It is curious as to why the second example doesn't compile, but I suspect it's mis-leading error message as you can do

A { public int get() { return super.i; } };

compile but

A { public int get() { return i; } };

gives

error: non-static variable i cannot be referenced from a static context

which is clearly incorrect given super.i would have no meaning if this were a static context.

As Marko notes

A { public int get() { return this.i; } };

produces the error message

error: i has private access in E

which may be more approriate. I.e. you can access this field explictly, but not implicitly.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130