Access to variables in another class

Asked

Viewed 55 times

-1

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

I made an example to try to explain

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

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

And here’s the second class where I try to capture the value

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

At the exit of the second class he left as 0.

Any suggestions? Thank you!

  • What comes to be your class um and dois, which are actually classes with very bad names? What is the code of your setInte? As you stated inte?

  • As I said, these are just examples, so they have these names. public int inte;

  • I mean, if you used public int inte, then it was not global variable. To be a global variable, it would have to be public static int inte. In addition, global variables are not good programming practices, especially if public.

1 answer

2


They’re two different objects. In the first class you have an object where you arrow the value. In 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 use a Pattern design called Singleton ( Where Voce returns the same object instance)

For example:

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

  public class Classe2 {
     Classe1 = Classe1.getInstancia();
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.