# 4.1: The Deck Class

$$\newcommand{\vecs}{\overset { \rightharpoonup} {\mathbf{#1}} }$$ $$\newcommand{\vecd}{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}}$$$$\newcommand{\id}{\mathrm{id}}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\kernel}{\mathrm{null}\,}$$ $$\newcommand{\range}{\mathrm{range}\,}$$ $$\newcommand{\RealPart}{\mathrm{Re}}$$ $$\newcommand{\ImaginaryPart}{\mathrm{Im}}$$ $$\newcommand{\Argument}{\mathrm{Arg}}$$ $$\newcommand{\norm}{\| #1 \|}$$ $$\newcommand{\inner}{\langle #1, #2 \rangle}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\id}{\mathrm{id}}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\kernel}{\mathrm{null}\,}$$ $$\newcommand{\range}{\mathrm{range}\,}$$ $$\newcommand{\RealPart}{\mathrm{Re}}$$ $$\newcommand{\ImaginaryPart}{\mathrm{Im}}$$ $$\newcommand{\Argument}{\mathrm{Arg}}$$ $$\newcommand{\norm}{\| #1 \|}$$ $$\newcommand{\inner}{\langle #1, #2 \rangle}$$ $$\newcommand{\Span}{\mathrm{span}}$$

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. 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;
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.

This page titled 4.1: The Deck Class is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .