Java 在局部类中,如何引用封闭方法的阴影变量?
在学习Oracle教程时,我想到了这种情况:Java 在局部类中,如何引用封闭方法的阴影变量?,java,class,Java,Class,在学习Oracle教程时,我想到了这种情况: class HelloWorldApp { public String s = "string in outer class"; public void shout() { final String s = "string in enclosing method"; class out { public String s = "string in local class";
class HelloWorldApp {
public String s = "string in outer class";
public void shout() {
final String s = "string in enclosing method";
class out {
public String s = "string in local class";
public void show()
{
System.out.println(s);
System.out.println(HelloWorldApp.this.s);//reference the member of enclosing class
System.out.println(HelloWorldApp.this.shout.s)//compiler complaints
}
}
out no = new out();
no.show();
}
public static void main(String[] args) {
HelloWorldApp h = new HelloWorldApp();
h.shout();
}
}
现在,我想在本例中引用方法shout()
的局部变量s
,但教程没有给出重点
我已经通过Google和StackOverflow进行了搜索,但我找不到正确的出路。你不能
JLS 6.4规定:
局部变量(§14.4)、形式参数(§8.4.1)、异常参数(§14.20)和局部类(§14.3)只能使用简单名称(§6.2)引用,而不能使用限定名称(§6.6)
6.4.1规定:
某些声明可能在其部分范围内被另一个同名声明所掩盖,在这种情况下,不能使用简单名称来引用已声明的实体
因此,您会遇到这样的情况:名称“只能”使用简单名称(6.4)引用,但它被隐藏,因此您无法使用简单名称(6.4.1)引用它。结论是你被卡住了 你不能
JLS 6.4规定:
局部变量(§14.4)、形式参数(§8.4.1)、异常参数(§14.20)和局部类(§14.3)只能使用简单名称(§6.2)引用,而不能使用限定名称(§6.6)
6.4.1规定:
某些声明可能在其部分范围内被另一个同名声明所掩盖,在这种情况下,不能使用简单名称来引用已声明的实体
因此,您会遇到这样的情况:名称“只能”使用简单名称(6.4)引用,但它被隐藏,因此您无法使用简单名称(6.4.1)引用它。结论是你被卡住了 @Makoto是的,你可以在方法
中声明类,现在,我想引用局部变量s
你没有提到你想引用它的地方。@YaroslavShabalin是的,他提到了。查看源代码中的注释。@Makoto是的,您可以在方法中声明类。现在,我想引用局部变量s
,您没有提到您想引用它的地方。@YaroslavShabalin是的,他引用了。请参阅源代码中的注释。