How to store data in a class with multiple variations

You can define a List object in your class.

For example a person that has credit cards:

public Class Person {

   private String name;
   private List<CreditCard> creditCards;

   // toString, equals, constructor, etc.

   public void setCreditCards(List<CreditCard> creditCards) {
      this.creditCards = creditCards;
   }

   public List<Creditcard> getCreditCards() {
      return this.creditCards;
   }

   // more getters and setters

And the Credit Card:

public Class CreditCard {

    private String number;
    private Date expiryDate;

    // getters and setters
}

And then you can make calls like this:

Person person = new Person();
List<CreditCard> cards = person.getCreditCards();
for(CreditCard card: cards) {
    String number = card.getNumber();
}

Leave a Comment