java - Accessing a private field from within the class refuses to compile -
this example not compile:
public class test{ private linkedlist<integer> lst = new linkedlist<>(); public static test of(int i){ return new test(){{ this.lst.addfirst(i); }}; } }
but does:
public class test{ private linkedlist<integer> lst = new linkedlist<>(); public static test of(int i){ test t = new test(); t.lst.addfirst(i); return t; } }
why? in both cases access private member class body.
with code
new test() { ... }
you declare , instantiate anonymous subclass of test
. , subclass not have access parent's private members.
see jls §15.9 (class instance creation expressions) , jls §15.9.5 (anonymous class declarations) more information
Comments
Post a Comment