Skip to Content
Think Java
book

Think Java

by Allen B. Downey, Chris Mayfield
May 2016
Beginner content levelBeginner
249 pages
5h 13m
English
O'Reilly Media, Inc.
Content preview from Think Java

Chapter 12. Arrays of Objects

In the remaining 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 “The Deck Class”, we create a Deck class that encapsulates an array of cards, and we write methods that operate on decks.

  • In Chapter 14, we introduce inheritance as a way to create new classes that extend existing classes. We then use all these classes to implement the card game Crazy Eights.

The code for this chapter is in Card.java, which is in the directory ch12 in the repository for this book. Instructions for downloading this code are in “Using the Code Examples”.

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn Java the Easy Way

Learn Java the Easy Way

Bryson Payne
Optimizing Java

Optimizing Java

Benjamin J. Evans, James Gough, Chris Newland

Publisher Resources

ISBN: 9781491929551Errata Page