Reputation: 978
I cannot access var
variable from inner class method. but java is accessing to class variable instead of local variable. How can I access to local variable instead of class variable from inner class method ?
class Foo {
void test() {
int var = 3;
class Inner {
int var = 1;
void print_var_of_test() {
System.out.println(var); // this line prints 1 why ?
// I want this line to print var of test (3) function.
}
}
}
}
Upvotes: 1
Views: 1073
Reputation: 131326
You cannot access a local variable defined in a method of the outer class from an inner class if the inner class defines already a variable with the same name.
You could use distinct names to distinguish them.
As workaround to keep the same variable names, you could change the signature of print_var_of_test()
to accept an int
.
In this way, outside the inner class you could pass the int var
variable as the method is invoked.
class Foo {
void test() {
int var = 3;
class Inner {
int var = 1;
void print_var_of_test(int var) {
System.out.println("outer var=" + var);
System.out.println("inner var=" + this.var);
}
}
Inner inner = new Inner();
inner.print_var_of_test(var);
}
}
Upvotes: 2
Reputation: 148
What about naming inner class var as varInner if you want to compare between it and the original one?
Upvotes: 0
Reputation: 31269
You do that by picking another name for either the local variable or the inner class variable.
Since the inner class and the method variable are defined in the same source method, you should always be able to change one of them. There is never a situation in which you don't have the permission/right/capability to change one but not the other.
Upvotes: 1