Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

java - 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. When I have 3 objects in the array, each element is the same as the 3rd, etc.

I'm not sure why this is happening, or how to correct it, and it's been baffling me for hours :/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...