简体   繁体   中英

How to access shadowed Outer class variable from Inner class?

This is not straight forward question. In my case the outer class variable and the inner class setter method's argument name is same. like:

class Problem {
    String s;
    int p;
    class Inner {
        String testMethod() {
         return  s = "Set from Inner";
        }
        void setP(int p)
        {
            p=p;  //it will do self assignment
        }
    }


}

now I cant initialize outer class instance variable p with this.p=p as it indicates the inner class. again I cannot do Problem.p=p; it gets an error. Now how can I assign outer p, keeping the inner Class method setP(int p) 's argument the same name p ?

这是你应该/应该做的:

Problem.this.p

用于引用外部类似的

Problem.this.p = p;

use this

class Problem {
String s;
int p;
class Inner {
    String testMethod() {
     return  s = "Set from Inner";
    }
    void setP(int p)
    {
        Problem.this.p=p;  //it will do assignment
    }
  }
}
class Problem {
String s;
int p;
class Inner {
    String testMethod() {
     return  s = "Set from Inner";
    }
    void setP(int p)
    {
        Problem.this.p=p;  //it will do assignment to p of outer class
    }
}
}

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