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

前端 未结 4 908
无人及你
无人及你 2020-12-11 11:35

I have the following code:

public static void main(String[] args) {
  Player players[] = new Player[2];
  Scanner kb = new Scanner(System.in);
  System.out.p         


        
相关标签:
4条回答
  • 2020-12-11 11:56

    Name field should not be static. Static means that the variable is actually global and shared across all class instances.

    0 讨论(0)
  • 2020-12-11 12:02

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-11 12:04

    With the keyword static you have made name a class variable which is NOT an instance variable. A class variable is common to all the objects. Click for some more reading.

    0 讨论(0)
  • 2020-12-11 12:08

    Change static string name to private string name

    0 讨论(0)
提交回复
热议问题