Nested class doen't change enclosing class field

46 views Asked by At

I try to write simple program, which works with nested class. I have noticed, that nested class can not change (or I did mistake) enclosing class field:

public class MyClass {

    private boolean bool = false;
    private NestedClass nestedClass = new NestedClass();

    private class NestedClass {

        private void print(){
               System.out.println(bool);
        }

        NestedClass(){
            bool = !bool;
        }
}

    MyClass(){
        nestedClass = new NestedClass();
    }

    public void getInfo(){
        nestedClass.print();
    }
}

After creating of new instance of MyClass, bool's value doesn't change:

public static void main(String[] args) {
    MyClass myClass = new MyClass();
    myClass.getInfo();
}

Output is false. But I expected true. What I did wrong?

1

There are 1 answers

0
Kishore Bandi On BEST ANSWER

I guess it did, the reason you're still seeing the value of bool as false is because its getting set twice (negated twice).

Once here

private NestedClass nestedClass = new NestedClass();

and second time

MyClass(){
    nestedClass = new NestedClass();
}

Both call the constructor of NestedClass twice which negates it twice resulting in false->true->false.