1

I'm trying to code a system to determine the type of a weapon and the damage of the weapon for a video game. I'm trying to instantiate two weapons with different stats, but when I use the method getType();, they return the same thing.

I tried using an ArrayList, but grabbing the type of the weapon from something such as (arraylist name here).get(0).getType(); and (arraylist name here).get(1).getType(); still return "AK-47".

ArrayList<Weapon> weapons = new ArrayList<Weapon>();
        Weapon weapon = new Weapon("Desert Eagle", 5);
        Weapon weapon2 = new Weapon("AK-47", 3);

        weapons.add(weapon);
        weapons.add(weapon2);

        System.out.println(weapon.getType());
        System.out.println(weapon2.getType());

Methods:

public class Weapon {
    static String type;
    static int damage;

    public Weapon(String type, int damage) {
        Weapon.type = type;
        Weapon.damage = damage;
    }

    public static String getType() {
        return type;
    }

}

I want weapon.getType(); to return "Desert Eagle" and weapon2.getType(); to return "AK-47".

I know it should be a simple answer, but I'm probably just over-complicating this for myself haha. Any help is appreciated, thanks!

ElliottV3
  • 21
  • 4
  • Your variables are static, and you are updating them on the constructor, this means that every moment you are instanciating the class, you are overwritting the values, type is going to be always the last Weapon name. Try changing `static` for private, and `Weapon.` for `this.` and instead of `public static` on the getType method, use only public – Davichete Aug 27 '19 at 21:57

3 Answers3

0

It is because your type is static Change it to private String type;

Nodir Nasirov
  • 1,488
  • 3
  • 26
  • 44
0

Remove static keywoard as it makes fields shared across every instance of that class

static String type;
static int damage;
Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

Remove static from type and damage in Weapon. static means one value for the class globally, not one value per class instance (which is what you want). Also, this.type = type; and this.damage = damage; in the constructor.

public class Weapon {
    private String type;
    private int damage;

    public Weapon(String type, int damage) {
        this.type = type;
        this.damage = damage;
    }

    public String getType() {
        return type;
    }
}

Also, you aren't currently using any values from your List (you kept the references you created, and are calling through those references). And prefer programming to the List interface over the ArrayList type (and you could use the diamond operator <>). Like,

List<Weapon> weapons = new ArrayList<>();
weapons.add(new Weapon("Desert Eagle", 5));
weapons.add(new Weapon("AK-47", 3));
for (Weapon w : weapons) {
    System.out.println(w.getType());
}

Outputs

Desert Eagle
AK-47
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249