Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Updated value of variable from another class.

3243443May 22 2016 — edited Oct 17 2016

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 !!!

This post has been answered by karianna on May 23 2016
Jump to Answer

Comments

Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Nov 9 2016
Added on May 22 2016
6 comments
1,339 views