Search code examples
javaencapsulation

Manipulate public variable of a different class that you are a public object of


I want to access a public variable from class Alpha in class Beta but the compiler says that that variable is undefined for class Beta. Note that Beta itself is also a public object of Alpha.

public class Alpha
{
   public Beta b = new Beta();
   public Boolean theVariable = true;

   public static void main(String[] args) throws IOException 
   {
      Alpha alpha = new Alpha();
   }
}

public class Beta
{
   // Perform an action
   theVariable = false; //This step is considered invalid 
}

I've tried making a method to retrieve it and several other things but I must be missing something because I cannot get it to accept this.


Solution

  • If the instance of Beta will only be accessed by the instance of Alpha, you should probably implement an inner class relation.

    Declare your "shared" variable first, then your inner class. After that, you can create instances of Beta and do whatever with the "shared" variable.

    public class Alpha
    {
        public boolean theVariable = true;
    
        public class Beta
        {
           // Perform an action
           public void doSomething() {
               theVariable = false; // Should now be ok
           }
        }
    
        public Beta b;
    
        // constructor
        public Alpha() {
            b = new Beta();
        }
    
        // do something with Beta
        public void doSomethingWithBeta() {
            b.doSomething();
        }
    }