Accessing outer class variable in inner class

Assuming your outer class is called Outer, from the scope of the inner class(non-static), Outer.this.foo to get at the field.

For example,

Outer.this.foo=new ArrayList<>();

where Outer is the name of the class and foo identifies the field.

You can also grab it directly as foo=new Baz() but it’ll pick the inner field if there’s a naming conflict due to shadowing.

if it’s a static inner class, you need an explicit instance:

outerInstance.foo=new ArrayList<>();

or if the field to access is static, access it as usual with:

Outer.staticFoo=new ArrayList<>();

Leave a Comment