Peter Chung Peter Chung - 2 months ago 4x
Java Question

can you create an instance of an object dynamically in Java?

I'm trying to make a blackjack game using Java on console. I'm at the stage where I need to decide how many players will be participating in each round. Before every round begins, console asks the user to type in how many players will be playing this round and create player object corresponding to that number. The restriction is from 0 to 5. I need to figure out how I'm going to create 1~5 Player objects based on the input. How would you create instance(s) of an object dynamically in java? I know you can do switch statements but was wondering if there is another way.


If you execute new Player() in a loop it will generate as many instances as you execute the loop. In your case the question is most likely not how to actually generate the players, but how to remeber them for later use. You do that by storing them in a collection or array:

List<Player> players = new ArrayList<>();
for(int i=0;i<number;i++) {
    players.add(new Player(i));

In this case I generate as many players as number and will pass the actual number to the constructor of the Player instance.

If you really want to generate instances of different classes (for example all implementing the Player interface) you would have to do this hardcoded (like the switch statement you mentioned) or with reflection. In the later case you need a array/collection of the actual class names or a rule how to generate them. But I really think having all players from the same class is the way to go.