Why?
It's because Object
is the static type of the variable o
, and Object
doesn't have the property x
. The following fails to compile for the exact same reason:
public class X {
public int x;
public static void main(String[] args) {
Object o = new X();
o.x = 3;
}
}
Hopefully, your Java intuition is right on this example and you expect this to fail. So just transplant that intuition to your example.
How to access fields declared inside anonymous object?
Same way as you'd access x
in my example: reflection.
Object o = new X();
o.getClass().getField("x").setInt(o, 3);
Why does it let me make public fields if I can't use them?
If it didn't let you make public fields, even reflection wouldn't work for you, at least not as simply as above.