在本地类中,如何引用封闭方法的阴影变量?

 xiaoliangtang 发布于 2023-02-07 19:37

在从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";
            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();
    }
}

现在,我想在这种情况下引用s方法的局部变量shout(),但是教程没有说明这一点.

我已经通过谷歌和StackOverflow进行了搜索,但我无法找到正确的方法.

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)引用它.结论是你被困住了.

    2023-02-07 19:38 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有