简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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