创建新对象会更改先前对象的实例变量

时间:2013-06-13 22:56:21

标签: variables object instance

以下是我的一些代码:

           PlayerInfo P1 = new PlayerInfo();
            P1.setInfo(1);
            System.out.println("" + P1.X + "," + P1.Y);
            PlayerInfo P2 =  new PlayerInfo();
            P2.setInfo(2);
            System.out.println("" + P1.X + "," + P1.Y);
            PlayerInfo P3 = new PlayerInfo();
            P3.setInfo(3);
            System.out.println("" + P1.X + "," + P1.Y);
            PlayerInfo P4 = new PlayerInfo();
            P4.setInfo(4);
            System.out.println("" + P1.X + "," + P1.Y);

玩家信息定义为:

public class PlayerInfo{
public static int Range;
public static int X;
public static int Y;
public static int Score;
public static int Lives;
private static ImageIcon image;
public PlayerInfo(int Num){
    Range = 1;
        if(Num == 1){
            this.X = 0;
            this.Y = 0;
            //System.out.println("" + X + "," + Y);
            image = new ImageIcon("H:\\My Pictures\\BomberMan\\BMBlack.png");
        }
        else if(Num == 2){
            this.X = 16;
            this.Y = 0;
            //System.out.println("" + X + "," + Y);
            image = new ImageIcon("H:\\My Pictures\\BomberMan\\BMWhite.png");
        }
        else if(Num == 3){
            this.X = 0;
            this.Y = 16;
            //System.out.println("" + X + "," + Y);
            image = new ImageIcon("H:\\My Pictures\\BomberMan\\BMRed.png");
        }
        else if(Num == 4){
            this.X = 16;
            this.Y = 16;
            //System.out.println("" + X + "," + Y);
            image = new ImageIcon("H:\\My Pictures\\BomberMan\\BMBlue.png");
        }
    Score = 0;
    Lives = 3;
}

现在我的代码正在显示:

0,0

16,0

0.16

16,16-

何时显示:

0,0

0,0

0,0

0,0

因为P1.X和P1.Y初始化为0和0而不应该在我的代码中更改。 我不知道为什么它在改变P1.X和P1.Y值的时候我根本不碰它们。有人可以向我解释一下吗?注意:我已经尝试创建一个单独的方法来设置信息和一个PlayerInfo数组,但没有任何作用。提前谢谢。

1 个答案:

答案 0 :(得分:0)

if课程的所有PlayerInfo子句中,您要为XY分配值。例如:

 this.X = 0;
 this.Y = 0;

由于XY变量为static,因此值正在发生变化。 删除static中两个变量的PlayerInfo,然后您将获得所需的行为。

static变量在类的不同对象之间共享。因此,如果您分配了P1.X = 10,那么P2.XP3.XP4.X等也将成为10,因为所有对象都共享同一个变量。< / p>