0

I have a method where I pass a variable (in this case an integer but could just as easily be a String) and want to use the variable as the object name when initialising. For example:

public static void printPlayerSetup(int playerPosition, String name) {
  Player playerPosition = new HumanPlayer(name);
}

So for example, if playerPosition was "1" the new object created would be "1". Player is an abstract class and HumanPlayer is an extends this just to be clear.

user1488434
  • 409
  • 1
  • 4
  • 11
  • Pass it into the player via a constructor parameter or a setter method. – Hovercraft Full Of Eels Jun 23 '20 at 22:51
  • Note: Variable "names" aren't really all that important, don't exist for many objects, and *almost* don't exist in compiled code. If an object is referred to by several variables, which one represents the "name" for this object? Much more important are *object **references*** and how they can be obtained. – Hovercraft Full Of Eels Jun 23 '20 at 23:01
  • ... If you must associate an object with an int, a clean way to do this is by using a Map such as a `HashMap` or `ArrayList` depending on need, but again don't put too much reliance on variable names since non-final variables can change references at the drop of a hat, and objects can be referred to by more than one variable. – Hovercraft Full Of Eels Jun 23 '20 at 23:01
  • @HovercraftFullOfEels thank you for your help. I guess what I am trying to avoid is having to manually assign object names for each player "player1" "player2" etc. I will need to be able to refer to each object later on to access mutators or accessors ie player1.getName(); I wanted to generate the object name so that if the user inputs that there are going to be four players, 4 new objects will be created: player1, player2, player3, player 4. – user1488434 Jun 24 '20 at 06:43
  • Again, there is no such thing as "object name", and I think that you are confusing variables with objects. Please read or re-read the duplicate – Hovercraft Full Of Eels Jun 24 '20 at 09:48

0 Answers0