Overlapping object in Java

5.1k Views Asked by At

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.

4

There are 4 best solutions below

0
On

The attributes in your Player class such as name,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:

  public static String name;

to

  public String name;

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

0
On

That's because name is a static field in your Player class. And the static fields are shared by all the instances of a class. Therefore, you need to make the name as an instance variable, so that each instance will have their own copy of the it.

public String name; // Now each instance will have its own copy of name

and I'm guessing that the same needs to be done for score as well.

public int score;
2
On

public static String name;

should be

public String name;

or even better

private String name;

0
On

Because, your field is static,

  public static String name;

To change the name with object make it as instance(non-static)

  public String name;