gpt4 book ai didi

java - 如何将一个类实例传递给另一个类以便对其进行修改?

转载 作者:行者123 更新时间:2023-11-30 08:43:33 27 4
gpt4 key购买 nike

public class Player {
private int hp = 100;
//with appropriate getters and setters, constructors etc.
}

public class Main{
Player player1 = new Player();
Player player2 = new Player();
//etc.

fightMonster(player1); //<--- I want to pass player1 to keep track of HP
}

public class fightMonster(something about player1){ //not sure what to put inside the ();
player1.setHp(player1.getHp - 10); //monster attacks and does 10 dmg
}

目前我找不到将 Player 类 player1 的实例传递给我的 fightMonster 方法的方法,因为它在不同的类中。我想传递整个 player1 类,因为它最终将包括玩家库存、经验、以前的 hp 等。我能想到的唯一方法是拆分 player1 的每一行,比如传递 int hp 并返回到 main 并使用 player1.setHp(int hp)。这并不能解决更复杂的应用程序(从战斗中获得的库存元素、经验等)。

即使我可以像

这样创建 Player 类的新实例

播放器 currentPlayer = new Player();

然后以某种方式返回 Main 将所有值匹配在一起...

第一次发帖,请多多指教!

最佳答案

假设您要执行一个具有一个参数的方法。你可以有这样的东西:

 String variable = "Hello";
doSomething(variable);

public void doSomething(String variable){}

调用方法的参数必须与调用方法时传递的变量类型相同。

所以对于你的情况我建议:

 public class Main {
Player player1 = new Player(); //You create a new Player
FightMonster actions = new FightMonster();

player1 = actions.getHit(player1); //You call the method "getHit" and pass the values of player1
}

public class FightMonster {
//The value of "player" its the same value of "player1" that you pass when you called this method
public Player getHit(Player player) {
player.setHp(player.getHp - 10); //You change the hp of the player
return player; //And return the new value of the player
}
}

返回值后,调用该方法时传递的播放器将返回新值。

关于java - 如何将一个类实例传递给另一个类以便对其进行修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34191562/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com