Tried to find this on many forums but can't find the solution or reason for the solution. I'm trying to get the updated value of a variable from other class by it's reference. The class containing the variable gets the updated value but the other class which creates a reference of the previous class still gets the old value. Here is a sample code:
class A {
private boolean state;
boolean getState() {
return state;
}
}
In the above class, the value of boolean variable state, keeps on changing by an ActionEvent.
class B {
void go() {
A a = new A();
while(true) {
if(a.getState()) {
//CODE
}
}
}
}
Here, a.getState(), never returns true, even when class A has contains updated state. Please suggest.
Here are some solutions that I found but can't find the reason::
1:
class B {
void go() {
A a = new A();
while(true) {
System.out.println(a.getState()); // strange, but works
if(a.getState()) {
//CODE
}
}
}
}
2:
class B {
void go() {
A a = new A();
A aa;
while(true) {
aa = a; // again, works!
if(a.getState()) {
//CODE
}
}
}
}
Please suggest !!!