简体   繁体   English

Java 将类的变量与类的另一个实例混淆

[英]Java confuses variables of a class with another instance of a class

I'm creating a program that has creatures battle each other.我正在创建一个让生物互相争斗的程序。 I have a class called Creature, which takes integer inputs for attack, speed, and health, respectively.我有一个名为 Creature 的类,它分别采用整数输入来表示攻击、速度和健康。 Whenever I try to make a new instance of the Creature class, and try to reference it using methods, it thinks I'm talking about the newest instance of the class.每当我尝试创建 Creature 类的新实例,并尝试使用方法引用它时,它都认为我在谈论该类的最新实例。

Creature c = new Creature(1,2,3);
c.getStats();

This prints out Attack: 1 Speed: 2 Health: 3这会打印出攻击:1 速度:2 健康:3

However, if I create a new Creature...但是,如果我创建一个新的生物...

Creature c = new Creature(1,2,3);
c.getStats();
Creature b = new Creature(9,9,9);
c.getStats();

As you can see, I'm referencing the same creature twice.如您所见,我两次引用同一个生物。 But, I get different results.但是,我得到了不同的结果。 Even if I specifically state the creature I'm talking about is c, it'll go for the newest instance of the Creature class instead.即使我特别声明我正在谈论的生物是 c,它也会改为使用 Creature 类的最新实例。 I believe what's happening is that Java is replacing c's variables with.我相信正在发生的事情是 Java 正在替换 c 的变量。 What can I do to fix this?我能做些什么来解决这个问题?

Your problem is clearly on the line of code that you instantiate (create) the second Creature object called b .您的问题显然出在您实例化(创建)名为b的第二个Creature对象的代码行上。 Since you didn't post your constructor for Creature , I guess in the constructor you assigned the values passed in to a static variable.由于您没有发布Creature的构造函数,我猜在构造函数中您分配了传递给静态变量的值。 Every class has one static variable per application domain.每个类的每个应用程序域都有一个静态变量。

So that's why you get different results.所以这就是为什么你会得到不同的结果。 Static variables change no matter which object you call on.无论您调用哪个对象,静态变量都会发生变化。 Thus, calling the constructor the second time will overwrite the value that you just assigned to the static variable.因此,第二次调用构造函数将覆盖您刚刚分配给静态变量的值。

Now you can try creating another Creature and call现在你可以尝试创建另一个Creature并调用

c.getStats()

again and you will see different results.再次,你会看到不同的结果。

To solve this, you need to go into your Creature class and look for the variables that stores the stats of the creatures.要解决这个问题,您需要进入Creature类并查找存储生物统计数据的变量。 There should be a word " static ".应该有一个词“ static ”。 And you should delete that.你应该删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM