gpt4 book ai didi

java - 如何访问由构造函数创建的对象变量

转载 作者:行者123 更新时间:2023-12-01 19:39:36 24 4
gpt4 key购买 nike

我有 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;

}

如何访问之前创建的对象?

最佳答案

当你定义

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

您仅为函数 continueRound1 定义 ROCK round1Rock。为了让 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;

}

关于java - 如何访问由构造函数创建的对象变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55757437/

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