首页 > 解决方案 > 如何访问由构造函数生成的对象变量

问题描述

我有 2 个按钮,1 个使用 round1rock 中的构造函数类,而其他 1 个尝试访问这些参数。我的代码有什么问题?

构造函数类

public ROCK(int hp, int stamina, int attack, int speed, String type){
   this.hp=hp;  
   this.stamina= stamina;
   this.attack= attack;
   this.speed = speed;
   this.type = type;
}

2个按钮:

private void continueRound1 (ActionEvent event){
       ROCK round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
    }
    private void Attack (ActionEvent event){
        round1Rock.hp = 12;

    }

我如何访问以前制作的对象?

标签: javafxml

解决方案


当你定义

private void continueRound1 (ActionEvent event){
   ROCK round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}

ROCK round1Rock只是为函数定义continueRound1。要Attack访问该对象,您需要round1Rock在类级别上进行定义。

尝试:

ROCK round1Rock = null;

private void continueRound1 (ActionEvent event){
  round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}
private void Attack (ActionEvent event){
    round1Rock.hp = 12;

}

推荐阅读