简体   繁体   中英

How can I access to local variable from inner class method?

I cannot access var variable from inner class method. but java is accessing to class variable instead of local variable. How can I access to local variable instead of class variable from inner class method ?

class Foo {
    void test() {
        int var = 3;

        class Inner {
            int var = 1;

            void print_var_of_test() {
                System.out.println(var); // this line prints 1 why ?
                // I want this line to print var of test (3) function.
            }
        }
    }
}

You cannot access a local variable defined in a method of the outer class from an inner class if the inner class defines already a variable with the same name.
You could use distinct names to distinguish them.

As workaround to keep the same variable names, you could change the signature of print_var_of_test() to accept an int .
In this way, outside the inner class you could pass the int var variable as the method is invoked.

class Foo {

  void test() {
    int var = 3;

    class Inner {
        int var = 1;

        void print_var_of_test(int var) {
          System.out.println("outer var=" + var);
          System.out.println("inner var=" + this.var);
        }
    }

    Inner inner = new Inner();
    inner.print_var_of_test(var);
  }

}

You do that by picking another name for either the local variable or the inner class variable.

Since the inner class and the method variable are defined in the same source method, you should always be able to change one of them. There is never a situation in which you don't have the permission/right/capability to change one but not the other.

如果要将内部类var命名为varInner,如果要将它与原始类进行比较,那该怎么办?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM