我有一个静态内部类,我想在其中使用外部类的实例变量。目前,我必须以“Outerclass.this.instanceVariable”这种格式使用它,这看起来很奇怪,有没有更简单的方法来访问外部类的实例字段?
Public class Outer
{
private int x;
private int y;
private static class Inner implements Comparator<Point>
{
int xCoordinate = Outer.this.x; // any easier way to access outer x ?
}
}
A static
嵌套类不能引用外部类实例,因为它是static
,没有相关的外部类实例。如果您希望静态嵌套类引用外部类,请将实例作为构造函数参数传递。
public class Outer
{
private int x;
private int y;
private static class Inner implements Comparator<Point>
{
int xCoordinate;
public Inner(Outer outer) {
xCoordinate = outer.x;
}
}
}
如果你的意思是内部(非static
嵌套)类和不存在变量名称冲突(即两个变量名称相同),可以直接引用外部类变量
public class Outer
{
private int x;
private int y;
private class Inner
{
int xCoordinate = x;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)