Java:如何使用"this"访问外部类的实例变量?

Ton*_*yGW 2 java field class instance outer-join

我有一个静态内部类,我想在其中使用外部类的实例变量.目前,我必须以这种格式"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 ?
}
}
Run Code Online (Sandbox Code Playgroud)

Sot*_*lis 6

一个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;       
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你的意思是内部(非static嵌套)类并且没有变量名称冲突(即两个变量都称为同名),则可以直接引用外部类变量

public class Outer
{
    private int x;
    private int y;
    private class Inner 
    {    
        int xCoordinate = x;
    }
}
Run Code Online (Sandbox Code Playgroud)