Java 隐藏变量,并访问它们?
我有一个代码,我有一个小问题Java 隐藏变量,并访问它们?,java,class,scope,local,shadowing,Java,Class,Scope,Local,Shadowing,我有一个代码,我有一个小问题 public class Out { int value = 7; void print() { int value = 9;//how to access this variable class Local { int value = 11; void print() { int value = 13; System.out.println("Value in method: " +
public class Out {
int value = 7;
void print() {
int value = 9;//how to access this variable
class Local {
int value = 11;
void print() {
int value = 13;
System.out.println("Value in method: " + value);
System.out.println("Value in local class: " + this.value);
System.out.println("Value in method of outer class: " + value);//here
System.out.println("Value in outer class: " + Out.this.value);
}
}
}
}
上面的代码描述了我的问题。您不能这样做,因为它需要传递到Local的构造函数中,因为它不是类的成员字段,而是一个局部方法变量
正如Andy所建议的,您可以使用不同的名称使其成为final,在这种情况下,编译器将隐式地将其传递给本地构造函数,并将其保存为Local的成员字段(您可以使用javap查看详细信息)。如果您想在本地内部类中使用局部变量,那么我们应该将该变量声明为final 请尝试使用此代码
int value = 7;
void print() {
final int value1 = 9;//change the variable name here.
//Otherwise this value is overwritten by the variable value inside Inner class method
class Local {
int value = 11;
void print() {
int value = 13;
System.out.println("Value in method: " + value);
System.out.println("Value in local class: " + this.value);
System.out.println("Value in method of outer class: " + value1);//here
System.out.println("Value in outer class: " + Out.this.value);
}
}
Local l1 = new Local();
l1.print();
}
public static void main(String[] args) {
Out o1 = new Out();
o1.print();
}
谢谢。不,它没有描述您的问题,只是代码。请确切说明问题所在。尝试使用其他名称调用变量。并最终确定。清楚准确地描述问题。他想要一种不更改名称的方式从外部类(int value=9)中的方法访问值。