Accessing private instance variable of inner class from outer class

狂风中的少年 提交于 2019-12-13 04:14:00

问题


Why isn't this code working

public class BB
{
    private class A
    {
        private int x;
    }

    public static void main(String[] args)
    {
        A a = new A();
        a.x = 100;
        System.out.println(a.x);
    }
}

while this code is working?

public class BB
{
    private class A
    {
        private int x;
    }

    static int y = 3;

    public static void main(String[] args)
    {
        BB b = new BB();
        b.compile();
        System.out.println("y = "+ y);
    }
    public void compile()
    {
        A a = new A();
        a.x = 100;
        System.out.println(a.x);
        System.out.println("y = "+ y);
    }
}

In first code, When I am trying to refer to instance variable 'x' of inner class 'A' by an object of inner class 'a', I am getting an error saying that I'm using inner class in static context. There is no error while doing the same in some other method.


回答1:


Your error has nothing to do with field access. Compilation fails for this line:

A a = new A();

Reason: you cannot instantiate an inner class without an enclosing instance, which is exactly what that line of code tries to do. You could write instead

A a = (new BB()).new A();

which would provide an enclosing instance inline. Then you will be able to access the private field as well.

Alternatively, just make the A class static, which means it does not have an enclosing instance.




回答2:


private class A is like an instance member and we can not use instance member inside static method without making its object. So first we need to object of outer class than we can use instance inner class. And below code is working fine.

class BB { private class A { private int x; }

public static void main(String[] args)
{
    BB bb = new BB();
    BB.A a = bb.new A();
    a.x = 100;
    System.out.println(a.x);
}

}



来源:https://stackoverflow.com/questions/18825718/accessing-private-instance-variable-of-inner-class-from-outer-class

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