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.
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.
– user28595
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.
– Gean Carlos Brandão
How to copy objects in java
– user28595