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?
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
and second time
Both call the constructor of NestedClass twice which negates it twice resulting in
false
->true
->false
.