如何从Inner类访问阴影的外部类变量?
这不是直截了当的问题。 在我的例子中,外部类变量和内部类setter方法的参数名称是相同的。 喜欢:
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 } } }
现在我无法使用this.p=p
初始化外部类实例变量p,因为它表示内部类。 再一次我不能做问题Problem.p=p;
它出错了。 现在我如何分配外部p,保持内部类方法setP(int p)
的参数名称为p?
这是你应该/应该做的:
Problem.this.p
用于引用外部类似的
Problem.this.p = p;
用这个
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 } } }