我创建了类播放器的 2 个实例,但似乎最后创建的实例总是接管(重叠?)所有其他对象,这里有什么问题?
这是程序:
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());
}
}
这是输出
Player 3
这就是类(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;
}
}
我尝试寻找其他类似的问题,但我发现的每个问题都太复杂,我无法真正理解。
最佳答案
Player
类中的属性,例如 name
、score
、dice
等被定义为类变量(静态
)而不是实例变量(非静态)。类/静态变量由所有对象共享,因此您会看到这种行为。尝试改变这个:
public static String name;
至
public String name;
明智地决定哪些内容需要声明为类变量,哪些内容需要声明为成员变量。在此处了解有关实例和类成员的更多信息:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
关于java - Java中的重叠对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20233579/