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 13. Objects of Arrays

In the previous chapter, we defined a class to represent cards and used an array of Card objects to represent a deck.

In this chapter, we take another step toward object-oriented programming by defining a class to represent a deck of cards. And we present algorithms for shuffling and sorting arrays.

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

The Deck Class

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 shows what a Deck looks like with no cards.

Figure 13-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 “Arrays of Cards”; we just turned it into a constructor. We can now ...

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