Java Static variable assignment and update

Asked

Viewed 488 times

1

I have a problem with a static variable. In the code I assign a variable that is not Static, the contents of a static variable. Then I update the static variable, only the variable that received the Static value there at the beginning is updating together and I don’t understand why this is happening. Type, I want to store the value of the variable Static in another variable at the beginning of the code, so I can use it later. But this other variable is updating together and I don’t understand why.

public class Jogador {
    public static Heroi jogador;   
    public static Item armaEquipada;
    public static Item defesaEquipada;
    public static Personagem oponente;
    public static int IdSala;

    public Jogador(){
        jogador = new Heroi("Optimus", 10, 100, 50, 100);
        oponente = new Vilao("", 0, 0);

    }
}

Here are the types of variables:

public Heroi EstadoAnteriorHeroi = null;
public Personagem EstadoAnteriorVilao;

Here are the assignments:

EstadoAnteriorVilao = Jogador.oponente; 
EstadoAnteriorHeroi = Jogador.jogador; // guarda os atributos anteriores do heroi se ele morrer e ainda tiver vidas;
System.out.println("Nome vilao: "+EstadoAnteriorVilao.getEnergia());

Then I update the attributes of the Player.opponent only that somehow I don’t understand Statenteriorvilao gets the same changes.

If you can help me understand what happens.

  • 2

    Simple, you are not assigning a "copy" of the static variable, but its reference in memory, which is why it changes also in the non-static variable if you change the content of the object of the static variable.

  • How do I save only the contents of the variable and not its reference in memory. Type in C when I use * to pick up the contents of a pointer.

1 answer

0


Search for Cloneable by

Example:

public class Jogador implements Cloneable {

Jogador getClone() {
    try {
        return (Jogador) super.clone();
    } catch (CloneNotSupportedException e) {
        return this;
    }
}

}

Browser other questions tagged

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