隐藏变量,并访问它们?

时间:2015-05-05 07:03:33

标签: 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: " + 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);
      }
    }
  }
}

上面的代码描述了我的问题。

2 个答案:

答案 0 :(得分:2)

只是你不能,因为它需要传递给Local的构造函数,因为它不是类的成员字段,而是本地方法变量。

正如Andy所建议的那样,你可以使用不同的名称使其成为最终版本,在这种情况下,编译器会将其隐式传递给Local构造函数,并将其保存为Local的成员字段(可以使用javap查看详情)。

答案 1 :(得分:0)

如果要在本地内部类中使用局部变量,那么我们应该将该变量声明为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();
}

感谢。