简体   繁体   English

如何从Inner类访问阴影的外部类变量?

[英]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. 在我的例子中,外部类变量和内部类setter方法的参数名称是相同的。 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. 现在我无法使用this.p=p初始化外部类实例变量p,因为它表示内部类。 again I cannot do Problem.p=p; 再一次我不能做问题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 ? 现在我如何分配外部p,保持内部类方法setP(int p)的参数同名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
    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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