• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 192
  • Last Modified:

(Java) Array of Objects Creates Only One Object?

I have an array of the class Player, but it appears to create only one object which every element of the array references. This is the code I am using (in two seperate files):

public class Player {

      private static String name;

      public static void setName(String Name) {
            name = Name.trim();
      }

      public static String getName() {
            return name;
      }

}

public class TestPlayer {

      public static void main(String[] args) {
            Player[] player = new Player[2];
            player[0].setName("A");
            System.out.println(player[0].getName());
            player[1].setName("B");
            System.out.println(player[0].getName());
            System.out.println(player[1].getName());
            player[0].setName("A");
            System.out.println(player[0].getName());
            System.out.println(player[1].getName());
      }

}

When I run TestPlayer, it outputs the following:
A
B
B
A
A

While the output I expected was:
A
A
B
A
B

I need to know how to define the player array so that each element of the array contains a different object.
0
Jshadias
Asked:
Jshadias
  • 2
1 Solution
 
vippxCommented:
Hi,

Your problem is the use of keyword 'static'. Static makes a member of a class specific to the class and not each instance. simply put, static methods are common to all instances(objects) of the class. Just remove all static keyowrds from your player class and try again.

If you have a doubt regarding this, feel free to ask again.
0
 
vippxCommented:
btwe dont remove static of your main method of your TestPLayer class. That is required for having your main method visible to the virtual machine during execution. BUt u can safely remove all the static keyowrds in your player class
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now