36

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?

4
  • 1
    Static inner class or non-static? Commented Jul 10, 2013 at 19:04
  • 3
    @DuncanJones: inner classes are always non-static. Have a look at here.. docs.oracle.com/javase/tutorial/java/javaOO/nested.html Commented Jul 10, 2013 at 19:07
  • 2
    @VishalK Thanks, I've been mistakenly calling nested classes inner classes for years. Whoops! Commented Jul 10, 2013 at 19:11
  • I think this post is later than op's time when s/he asked, but it is a good reference programiz.com/java-programming/nested-inner-class Commented Sep 24, 2020 at 0:52

2 Answers 2

67

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<>();
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks for reply,Here my question is if inner class and outer class uses the variable at a time there might be a chance of concurrent issues.But, the inner classes uses variable as how two methods of a class use.so, we should need to use synchhronization to handle this with inner class.
@user5 No, not beyond any synchronization you would need to do in any other case. Inner and outer classes do not cause new threads to be created.
2

Answer: Outer class variables in java are accessible because of lexical scope.

What is a lexical scope?

The scope defined in order in which code is authored. Lets say your class structure is as follows

OuterMost  
   --Inner  
     --InnerMost

Then the inner most class will be able to access variables from inner as well outer most.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.