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);         }};     } } 

demo

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;     } } 

demo

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

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -