方法本地内部类成员作用域访问 [英] Method Local Inner Class Member scope access

查看:95
本文介绍了方法本地内部类成员作用域访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问与内部类成员实例名称相同的方法变量或内部类的方法局部变量?

How do I access the method variable having the same name as the inner class member instance or method local variable of the inner class?

    class A{
       int a = 10;     //1

       public void someMethodA(){
       final int a = 20;     //2

       class B{
       int a = 30;     //3

        public void someMethodB(){
        int a = 40;     //4

        System.out.println("a = "+a);  //access 4
        System.out.println("a = "+this.a);   //access 3
        System.out.println("a = "+A.this.a);    //access 1
        System.out.println(?????);     //how do I access value of a i.e 2

       }
      }
    }
   }

推荐答案

否.你不能那样做.原因是,位置 2 中的变量a是局部变量,在封闭范围内只能使用其简单名称进行访问.来自 JLS§ 6.4 :

No. You can't do that. The reason being, the variable a in position 2 is a local variable, which can only be accessed with it's simple name, in the enclosing scope. From JLS §6.4:

只能使用简单名称(§6.2)引用局部变量(§14.4),形式参数(§8.4.1),异常参数(§14.20)和局部类(§14.3).限定名称(§6.6).

A local variable (§14.4), formal parameter (§8.4.1), exception parameter (§14.20), and local class (§14.3) can only be referred to using a simple name (§6.2), not a qualified name (§6.6).

现在,这清除了您只能使用a访问该变量.但是,方法本地类B中还有另一个变量,该变量在位置 2 中遮盖了该局部变量a,再次在位置 4 中遮盖了该局部变量.

Now, this clears that you can only access that variable with just a. But, you have another variable in method local class B which shadows that local variable a in position 2, which is again shadowed by local variable in position 4.

现在在print语句中,a将从最接近的作用域访问该变量,即位于位置 4 的局部变量.如果删除该变量,它将在位置 3 处打印该变量.然后,如果将其删除,它将在位置 2 处打印该变量.

Now in print statement, a would access the variable from nearmost enclosing scope, that is local variable at position 4. If you remove that variable, it will print the variable at position 3. And then if you remove it, it will print the variable at position 2.

因此,重点是,无法访问位置 2 的局部变量a,因为它已被遮盖.

So, the point is, there is no way to access the local variable a at position 2, because that is shadowed.

这篇关于方法本地内部类成员作用域访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆