IRock
IRock

Reputation: 127

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.

Upvotes: 0

Views: 7161

Answers (2)

Deepak
Deepak

Reputation: 143

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

}

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200158

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.

Upvotes: 10

Related Questions