有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java获取调用当前对象的对象

我有一个职业玩家,有一个对象玩家_1,还有一个职业武器。 从我的对象player_1,我调用一个位于类wearmplayer_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)
}

但我不知道如何从武器物体上找到玩家1, 有没有办法做到这一点,而不是把方法改成这样: void changeDurability(Player player, int x)

提前感谢您的帮助解答


共 (2) 个答案

  1. # 1 楼答案

    武器是否损坏是属于该武器的信息,而不是使用该武器的玩家的信息。我建议您将isBroken变量移动到Weapon类,然后在Player类中使用如下方法:

    boolean isWeaponBroken(){
        return this.getWeapon().isBroken
    }
    
  2. # 2 楼答案

    你可以修正你对玩家武器的召唤,而不必修正武器等级:

    // Player code
    public void changeWeaponDurability(int x) {
        player_1.getWeapon().changeDurability(x);
        if (player_1.getWeapon().getDurability() <= 0) {
            player_1.setWeaponBroken(true);
        }
    }