# 3.1: Card Objects

If you are unfamiliar with traditional playing cards, now would be a good time to get a deck or read through https://en.Wikipedia.org/wiki/Standard_52-card_deck.

There are 52 cards in a standard deck. Each card belongs to one of four suits and one of 13 ranks. The suits are Spades, Hearts, Diamonds, and Clubs. The ranks are Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King.

If we want to define a class to represent a playing card, it is pretty obvious what the instance variables should be: rank and suit. It is not as obvious what types they should be. One possibility is a String containing things like "Spade" for suits and "Queen" for ranks. A problem with this design is that it would not be easy to compare cards to see which had a higher rank or suit.

An alternative is to use integers to encode the ranks and suits. By “encode” we don’t mean to encrypt or translate into a secret code. We mean “define a mapping between a sequence of numbers and the things we want to represent.”

Here is a mapping for suits:

 Clubs ↦ 0 Diamonds ↦ 1 Hearts ↦ 2 Spades ↦ 3

We use the mathematical symbol ↦ to make it clear that these mappings are not part of the program. They are part of the program design, but they never appear explicitly in the code.

Each of the numerical ranks (2 through 10) maps to the corresponding integer, and for face cards:

 Ace ↦ 1 Jack ↦ 11 Queen ↦ 12 King ↦ 13

So far, the class definition for the Card type looks like this:

public class Card {
private int rank;
private int suit;

public Card(int rank, int suit) {
this.rank = rank;
this.suit = suit;
}
}


The instance variables are private: we can access them from inside this class, but not from other classes.

The constructor takes a parameter for each instance variable. To create a Card object, we use the new operator:

Card threeOfClubs = new Card(3, 0);


The result is a reference to a Card that represents the 3 of Clubs.