Access to variables in another class [closed]

-1

I have to do a project for college and in it I have a menu of settings, which is in a class separated from the main one, but when I try to "save" such configurations the main class does not see the change and gets the original value . I tried to do with Gets and Sets.

I did an example to try to explain

This is the first class in inte is an integer and global variable

      JOptionPane.showMessageDialog(null, inte);
      setInte(10);
      JOptionPane.showMessageDialog(null, inte);
      new dois().setVisible(true);

And here is the second class where I try to capture the value

    um teste = new um ();
    JOptionPane.showMessageDialog(null, teste.getInte());

In the output of the second class it left as 0.

Any suggestions? Thanks!

    
asked by anonymous 20.10.2016 / 18:20

1 answer

2

They are two different objects. In the first class you have an object where you set the value. In the second class when doing um teste = new um (); you are creating a new object in memory, you are not accessing the previous object. What you can do is to use a design pattern called Singleton (Where you return the same object instance)

For example:

  public class Classe1 {
    Classe1 instancia;
    public static Classe1 getInstancia(){
        return instancia;
    }
  }

  public class Classe2 {
     Classe1 = Classe1.getInstancia();
  }
    
20.10.2016 / 18:31