0

I'm trying to create multiple instances of an object and store it in an array. However, the last instance of it overwrites the previous ones. Is their a way I can create each individual object?

I've tried creating an array and filling each individual object separately. I've also tried creating new instances of it.

class Card {
 private static String name;

 public Card(String name) {
  this.name = name;
 }

 public String getName() {
  return name;
 }
}

public class Main {
 static Card[] deck = new Card[5];
 public static void main(String args[]) {
  deck[0] = new Card("Ace");
  deck[1] = new Card("Club");

  System.out.println(deck[0].getName());
  System.out.println(deck[1].getName());
 }
}

The output of deck[0] should be "Ace" while deck[1] should be "Club". What is outputting is "Club" twice. How can I fix this?

Redux
  • 1

1 Answers1

2

The field name in your class Card is declared static. Remove the static keyword:

class Card {
 private String name;
 // ...
}

If something is static there can be only one.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
JustinKSU
  • 4,875
  • 2
  • 29
  • 51