I created 2 instances of my class player, but it seems as though the last instance created always takes over (overlaps?) All of the other objects, what is the issue here?
Here is the program:
public class Test
{
public static void main (String[] args)
{
Player player1 = new Player("Player 1");
Player player2 = new Player("Player 2");
Player player3 = new Player("Player 3");
System.out.println(player1.getName());
}
}
This is the output
Player 3
And this is the class
import java.util.Scanner;
import java.util.Random;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Player
{
public static String name;
public static int score;
public static Die[] dice = new Die[5];
public static JRadioButton[] rerollButton = new JRadioButton[5];
//----------------------------------------------------------------
// Constructor - initialize values
//----------------------------------------------------------------
public Player(String n)
{
name = n;
score = 0;
// initialize all dice and rerollButtons in their respective arrays
for (int i = 0; i < 5; i++) {
dice[i] = new Die();
rerollButton[i] = new JRadioButton();
}
}
public String getName()
{
return name;
}
}
I have tried to look for other similar questions but every one I found was far to complex for me to really understand.
The attributes in your
Player
class such asname
,score
,dice
etc are defined as class variables(static
) instead of instances variables(non-static). Class/static variables are shared by all the objects and hence you see that behavior. Try changing this:to
Make a wise decision what you need to declare as class variable and what as member variable. Learn more about instance and class members here:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html