简体   繁体   中英

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. 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 c = new Creature(1,2,3);
c.getStats();

This prints out Attack: 1 Speed: 2 Health: 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. I believe what's happening is that Java is replacing c's variables with. 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 . Since you didn't post your constructor for Creature , I guess in the constructor you assigned the values passed in to a static variable. 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

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. There should be a word " static ". And you should delete that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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