Alex Rivera | Logout

Private instance member access from anonymous static instance

Asked 2013-01-03T12:07:50.407
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;
}
Edit
Report

1 Answer

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.

answered 2013-01-03T14:36:22.680

Your Answer