0

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.

3
  • In the second code, you aren't accessing the inner class in a static context: you're accessing it from a method of the class BB. That's why you're not getting that error. Commented Sep 16, 2013 at 10:26
  • 1
    try BB b=new BB(); A a = b.new A(); Commented Sep 16, 2013 at 10:27
  • Your nested class should be static also. Commented Sep 16, 2013 at 10:35

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.