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

后端 未结 1 1792
悲&欢浪女
悲&欢浪女 2021-01-23 00:17

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

相关标签:
1条回答
  • 2021-01-23 00:25

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题