Reputation: 3264
I have code that looks like this:
player a=new player(4,10,2,3,"You",'@');
player b=new player(4,10,12,3,"Him",'@');
a.pickUp(new weapon("Lightsaber",true,1,1));
System.out.println(a.getPlayerInventory()[0]);
System.out.println(b.getPlayerInventory()[0]);
However, at this point, the output of this code tells me that the content's of B's inventory also include a lightsaber. (The same object that player A has.)
What are some possible reasons for this to occur in java? Could it have something to do with whether other methods are static or public/private or not?
I did try googling it, but couldn't find anything (probably because I do not know what this problem is called.)
Thank you for any help you can give me.
Upvotes: 0
Views: 67
Reputation: 32189
Without seeing the implementation of the player
class I can't say for sure, but the most likely explanation is that the array containing the player's inventory is declared as static
, which means all instances of the class would share the array.
Upvotes: 1
Reputation: 2976
If you have a player's inventory as static, then if A gets a lightsaber, every player will have that same lightsaber
Upvotes: 3