Skip to main content
Engineering LibreTexts

4.1: The Deck Class

  • Page ID
    15291
  • The main idea of this chapter is to create a Deck class that encapsulates an array of Cards. The initial class definition looks like this:

    public class Deck {
        private Card[] cards;
    
        public Deck(int n) {
            this.cards = new Card[n];
        }
    }
    

    The constructor initializes the instance variable with an array of n cards, but it doesn’t create any card objects. Figure 13.1.1 shows what a Deck looks like with no cards.

    State diagram of an unpopulated Deck object.
    Figure \(\PageIndex{1}\): State diagram of an unpopulated Deck object.

    We’ll add a second constructor that makes a standard 52-card deck and populates it with Card objects:

    public Deck() {
        this.cards = new Card[52];
        int index = 0;
        for (int suit = 0; suit <= 3; suit++) {
            for (int rank = 1; rank <= 13; rank++) {
                this.cards[index] = new Card(rank, suit);
                index++;
            }
        }
    }
    

    This method is similar to the example in Section 12.6; we just turned it into a constructor. We can now create a standard Deck like this:

    Deck deck = new Deck();
    

    Now that we have a Deck class, we have a logical place to put methods that pertain to decks. Looking at the methods we have written so far, one obvious candidate is printDeck from Section 12.6.

    public void print() {
        for (int i = 0; i < this.cards.length; i++) {
            System.out.println(this.cards[i]);
        }
    }
    

    When you transform a static method into an instance method, it usually gets shorter. We can simply type deck.print() to invoke the instance method.

    • Was this article helpful?