1
public class ShadowTest
{

    public int x = 0;

    class FirstLevel
    {
        {  // here not able to understand why it allows.

            x = 1;
        }

        void methodInFirstLevel()
        {
            System.out.println("x = " + x);
            // System.out.println("this.x = " + this.x);
            System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
        }
    }

    public static void main(String... args)
    {
        ShadowTest st = new ShadowTest();
        ShadowTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel();
    }
}

I'm not clear why, without brackets, it doesn't work and what the significance of the brackets is? Please explain in detail.

Dave Bower
  • 3,487
  • 26
  • 28
Shahaan Syed
  • 109
  • 3

3 Answers3

1

Because when you remove the brackets it considered as a declaration and you cannot declare the x with in the inner class again, since the outer have the variable with same name.

It is allowing with in the {} cause that considered as a initialization block when you create an instance, that executes.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

It is basically considered as a constructor there. Since you are new to java may be this will make sense to you if you write it as

public class ShadowTest {

public int x = 0;

class FirstLevel
{

    FirstLevel()     //Adding a proper costructor
    {                // here not able to understand why it allows.

        x = 1;
    }

    void methodInFirstLevel()
    {
        System.out.println("x = " + x);
        // System.out.println("this.x = " + this.x);
        System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
    }
}

public static void main(String... args)
{
    ShadowTest st = new ShadowTest();
    ShadowTest.FirstLevel fl = st.new FirstLevel();
    fl.methodInFirstLevel();
}
}

Check about constructors in here http://www.javatpoint.com/constructor

Vivek Anoop
  • 7
  • 1
  • 6
0

If You will remove the brackets then from instance block it will become declaration state. You already have same variable x as outer class member. If you declare the variable with some other name then it could be possible.

RCS
  • 1,370
  • 11
  • 27