Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 534
kiran Avatar asked Jul 10 '13 19:07

kiran


People also ask

Can inner class access outer class method?

Method Local inner classes can't use a local variable of the outer method until that local variable is not declared as final. For example, the following code generates a compiler error.

Can static inner class access outer class variables?

Unlike inner class, a static nested class cannot access the member variables of the outer class. It is because the static nested class doesn't require you to create an instance of the outer class.

Can inner class access outer class private variables C#?

The inner class can access any non-static member that has been declared in the outer class. Scope of a nested class is limited by the scope of its (outer) enclosing class. If nothing is specified, the nested class is private (default). Any class can be inherited into another class in C# (including a nested class).


2 Answers

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<>();
like image 131
nanofarad Avatar answered Oct 12 '22 14:10

nanofarad


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.

like image 2
Majeed Siddiqui Avatar answered Oct 12 '22 14:10

Majeed Siddiqui