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

可紊 提交于 2019-12-02 01:31:46

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