简体   繁体   English

为什么该对象数组中的每个元素都被最后一个对象覆盖?

[英]Why does each element in this array of objects get overwritten by the last object?

I have the following code: 我有以下代码:

public static void main(String[] args) {
  Player players[] = new Player[2];
  Scanner kb = new Scanner(System.in);
  System.out.println("Enter Player 1's name");
  players[0] = new Player(kb.nextLine());
  System.out.println("Enter Player 2's name");
  players[1] = new Player(kb.nextLine());
  System.out.println("Welcome "+ players[0].getName() + " and " + players[1].getName());    
}

It is meant to create a new player object and store the name of the player, while keeping all the objects in the array. 它旨在创建一个新的播放器对象并存储播放器的名称,同时将所有对象保留在数组中。

Here is the player class: 这是玩家类:

public class Player {
  static String name;
  public Player(String playerName) {
    name = playerName;
  }

  public String getName(){
    return name;
  } 
}

What actually happens is that it works when I just have 1 object, but when I have 2, each element in the array is the same as the second. 实际发生的情况是,当我只有1个对象时它起作用,但是当我有2个对象时,数组中的每个元素都与第二个相同。 When I have 3 objects in the array, each element is the same as the 3rd, etc. 当我在数组中有3个对象时,每个元素与第三个元素相同,依此类推。

I'm not sure why this is happening, or how to correct it, and it's been baffling me for hours :/ 我不确定为什么会这样,或者如何纠正它,这让我感到困惑了好几个小时:/

Its because of the static field. 这是由于静态字段。 Statics are used across object instances. 静态对象对象之间使用。 They are stored at class level. 它们存储在类级别。

Below code would work: 下面的代码可以工作:

class Player
{
    String name;

    public Player(String playerName)
    {
        name = playerName;
    }

    public String getName()
    {
        return name;
    }
}

将静态字符串名称更改为私有字符串名称

Name field should not be static. 名称字段不能为静态。 Static means that the variable is actually global and shared across all class instances. 静态意味着变量实际上是全局的,并且在所有类实例之间共享。

With the keyword static you have made name a class variable which is NOT an instance variable. 使用关键字static ,可以将一个类变量name不是实例变量的类。 A class variable is common to all the objects. 类变量是所有对象共有的。 Click for some more reading . 单击以获取更多阅读信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM