我需要访问另一个类中已经实例化的对象"player"



我正在学习Java(我是编程新手),我决定开始一个文本冒险项目的工作。我有一个Game类(拥有main方法)、Player类和Enemy类。敌人类有一个攻击方法,而玩家类有一个takeDamage方法。我在main方法中的Game类文件中创建了一个玩家对象,并且需要访问Enemy类中相同的player实例,以便操纵玩家的生命值变量等。

我尝试在敌人类的构造函数中传递游戏类的引用this.game = game(这在另一篇文章中提到过),但敌人职业仍然无法识别玩家对象。我有其他的课,但它们是不相关的。

public class Game
{
public static void main(String[] args)
{
//Declaration of main method
System.out.print(Art.logo);     //  Prints the logo found in the Art class
Text.Opener();  //  Calls Opener method from Text class. Displays opening story.
String playerName = Player.getPlayerName();       //    Calls getPlayerName function from Text class and stores return value in playerName
String playerGender = Player.getPlayerGender();     //  Calls getPlayerGender method from Player class
String playerClass = Player.getPlayerClass();       //  Calls getPlayerClass method from Player class
Player player = new Player(playerName, playerGender, playerClass);      //  Creates a new object instance of Player class,
          //  named player, using the data retrieved from the
          //  user using the methods called above
public class Enemy {
Game game;
String name;
String gender;
String eClass;
int health = 100;
final int maxHealth = 100;
int strength;
final int maxStrength = 100;
Enemy(String name, String gender, String eClass, int strength)
{
this.game = game;
name = this.name;
gender = this.gender;
eClass = this.eClass;
strength = this.strength;
}
public void attack(int currentStrength, String weapon)
{
System.out.println(this.name + " the " + this.eClass + " hits you with " + weapon);
game.player.health;
}

你不能使用game访问敌人职业中的玩家的原因。玩家是因为玩家只是一个变量。为了访问它,你需要使它成为Game的公共属性。像这样:

public class Game
{
public static Player player;
public static void main(String[] args)
{
//Declaration of main method
System.out.print(Art.logo);     //  Prints the logo found in the Art class
Text.Opener();  //  Calls Opener method from Text class. Displays opening story.
String playerName = Player.getPlayerName();       //    Calls getPlayerName function from Text class and stores return value in playerName
String playerGender = Player.getPlayerGender();     //  Calls getPlayerGender method from Player class
String playerClass = Player.getPlayerClass();       //  Calls getPlayerClass method from Player class
player = new Player(playerName, playerGender, playerClass);      //  Creates a new object instance of Player class,
      //  named player, using the data retrieved from the
      //  user using the methods called above

现在你可以通过

从任何地方访问播放器
Game.player

p。玩家是一个静态对象,所以你不再需要这一行了(顺便说一句,它没有做任何事情,因为没有名为"game"的变量)。作为参数传递)

this.game = game

编辑:

用这行设置参数"name"属性"name"的值(该值为零,因为您还没有初始化它)。因此,您可以使用构造函数传递的值覆盖该变量,并设置为null。

name = this.name;

相反,你需要用另一种方式:

this.name = name;

最新更新