Chapter 12. Arrays of Objects
During the next three chapters, we will develop programs that work with playing cards and decks of cards. Here is an outline of the road ahead:
In this chapter, we define a
Card
class and write methods that work with cards and arrays of cards.In Chapter 13, we define a
Deck
class that encapsulates an array of cards, and we write methods that operate on decks.In Chapter 14, we introduce a way to define new classes that extend existing classes. Then we use
Card
andDeck
to implement the game Crazy Eights.
There are 52 cards in a standard deck. Each card belongs to one of four suits and one of 13 ranks. The suits are Clubs, Diamonds, Hearts, and Spades. The ranks are Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King.
If you are unfamiliar with traditional playing cards, now would be a good time to get a deck or read through Wikipedia’s “Standard 52-card deck” entry.
Card Objects
If we want to define a class to represent a playing card, it is pretty clear 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 choice 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 to define a mapping between a sequence of numbers and ...
Get Think Java, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.