Search code examples
javaprivateinner-classes

Accessing private instance variable of inner class from outer class


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.


Solution

  • 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.