访问本地类中的阴影变量 [英] access to shadowed variable in local class

查看:80
本文介绍了访问本地类中的阴影变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,我为下面的示例感到困惑

i'm new in java and i confused for below example

public class Test {

   int testOne(){  //member method
       int x=5;
         class inTest  // local class in member method
           {
             void inTestOne(int x){
             System.out.print("x is "+x);
         //  System.out.print("this.x is "+this.x);
           }
  }
       inTest ins=new inTest(); // create an instance of inTest local class (inner class)
       ins.inTestOne(10);
       return 0;
   }
    public static void main(String[] args) {
   Test obj = new Test();
   obj.testOne();
}
}

为什么我无法在第8行中使用"this"关键字访问inTestOne()方法中的阴影变量

why i can't access to shadowed variable in inTestOne() method with "this" keyword in line 8

推荐答案

为什么我无法在第8行中使用"this"关键字访问inTestOne()方法中的阴影变量

why i can't access to shadowed variable in inTestOne() method with "this" keyword in line 8

因为x不是 类的成员变量;它是一个 local 变量.关键字this可用于访问该类的成员字段,而不是局部变量.

Because x is not a member variable of the class; it is a local variable. The keyword this can be used to access a member fields of the class, not local variables.

一旦变量被屏蔽,您将无法访问它.可以,因为变量和本地内部类都可以更改.如果要访问带阴影的变量,则只需重命名(或重命名带阴影的变量,对您而言更有意义).

Once a variable is shadowed, you have no access to it. This is OK, because both the variable and the local inner class are yours to change; if you want to access the shadowed variable, all you need to do is renaming it (or renaming the variable that shadows it, whatever makes more sense to you).

注意:不要忘记标记局部变量final,否则即使它没有被遮盖,您也将无法访问它.

Note: don't forget to mark the local variable final, otherwise you wouldn't be able to access it even when it is not shadowed.

这篇关于访问本地类中的阴影变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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