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

前端 未结 4 918
无人及你
无人及你 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 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;
        }
    }
    

提交回复
热议问题