I'm making a game in java and consistenetly get the strangest bug. I have a class called weapon. Then I create an instance of it called primary. After I create an instance and call it secondary. for some strange reason, primary gets overwritten with secondary's values. My instructor and I both looked at it and couldn't figure it out. Here's the code:
public class weapon {
static String type;
static String name;
static int weight;
static int damage;
static int dodge;
weapon(String c, String n, int w, int da, int dod) {
type = c;
name = n;
weight = w;
damage = da;
dodge = dod;
}
//getters
String getType(){
return type;
}
String getName(){
return name;
}
Integer getWeight(){
return weight;
}
Integer getDamage(){
return damage;
}
Integer getDodge(){
return dodge;
}
//setters
void setType(String c){
c=type;
}
void setName(String n){
n=name;
}
void setWeight(Integer w){
w=weight;
}
void setDamage(Integer da){
damage=da;
}
void setDodge(Integer dod){
dodge=dod;
}
}
/*At the top of my main class I create both instances like this because the instances are created in if statements and I need to access them.*/
weapon primary;
weapon secondary;
//I create primary like this earlier in the code like this
primary = new weapon("primary","sword", 8, 6, -1);
//and then when I run this I get the output "sword" "Heavy Sword".
System.out.println(primary.getName());
secondary = new weapon("secondary", "huge sword", 9, 7, -2);
System.out.println(primary.getName());
All your member variables are defined as static :
static String type;
static String name;
static int weight;
static int damage;
static int dodge;
That's why the values of the second instance override the first (since static members are class veriables - there is a single copy of them across all instances of the class).
Removing the static keyword would solve the problem.
All the properties of your Weapon
class are static, which means they are shared among all instances you create.
Remove static to make them instance variables instead, and you should be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With