Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

java - Accessing outer class variable in inner class

In inner classes, variables of outer class are accessible, but local variables of a method are not. I understood the part about local variables of a method not being accessible but I want to know why outer class variables are accessible?

My understanding is that as an inner class binds with the outer class, so as long as the parent is available, the child can access its parent variables. Am I correct?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...