Java: how to access outer class's instance variable by using “this”?

爱⌒轻易说出口 提交于 2019-12-02 03:57:46

问题


I have a static inner class, in which I want to use the outer class's instance variable. Currently, I have to use it in this format "Outerclass.this.instanceVariable", this looks so odd, is there any easier way to access the instance field of the outer class?

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 ?
}
}

回答1:


A static nested class cannot reference the outer class instance because it's static, there is no related outer class instance. If you want a static nested class to reference an outer class, pass an instance as a constructor argument.

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;       
        }
    }
}

If you meant an inner (non-static nested) class and there is no variable name collision (ie. both variables called the same name), you can directly reference the outer class variable

public class Outer
{
    private int x;
    private int y;
    private class Inner 
    {    
        int xCoordinate = x;
    }
}


来源:https://stackoverflow.com/questions/18729529/java-how-to-access-outer-classs-instance-variable-by-using-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!