1

I have a class Player, with a an object player_1, and an another class Weapon. From my object player_1 i call a method who is located in class Weapon player_1.getWeapon().changeDurability(int x)

void changeDurability( int x) {
// changing durability
// and then i want to do something like this :
if( durability <= 0) player1.setWeaponBroken(true)
}

But i don't know how to get the player1 from the Weapon object, and is there a way to do this instead of changing the method to something like this: void changeDurability(Player player, int x)

Thanks in advance for any helping answers.

SkyNalix
  • 57
  • 7
  • It is not advisable to get the object who called your method, see other questions like https://stackoverflow.com/questions/15329566/how-to-find-the-object-that-called-a-method-in-java or https://stackoverflow.com/questions/43072542/can-i-get-the-instance-of-the-calling-object-in-java. – Progman Apr 19 '20 at 18:46

2 Answers2

2

Whether or not a weapon is broken is information that belongs to that weapon, not to the player using it. I would recommend that you move the isBroken variable to the Weapon class and then have a method like this in your Player class:

boolean isWeaponBroken(){
    return this.getWeapon().isBroken
}
Simon Crane
  • 2,122
  • 2
  • 10
  • 21
1

You may fix your call to the player's weapon - without fixing Weapon class:

// Player code
public void changeWeaponDurability(int x) {
    player_1.getWeapon().changeDurability(x);
    if (player_1.getWeapon().getDurability() <= 0) {
        player_1.setWeaponBroken(true);
    }
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42