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