Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange runtime error declaring instance of class Java

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());
like image 222
user2774616 Avatar asked Mar 20 '23 00:03

user2774616


2 Answers

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.

like image 117
Eran Avatar answered Mar 21 '23 12:03

Eran


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.

like image 23
Keppil Avatar answered Mar 21 '23 13:03

Keppil