To implement this game, we need to represent a deck of cards, a discard pile, a draw pile, and a hand for each player. And we need to be able to deal, draw, and discard cards.
Deck class from the previous chapter meets some of these requirements, but there are two problems:
- Hands and piles have different sizes, and their sizes change as the game progresses. Our implementation of
Cardarray, and the size of an array can’t change.
- It’s not clear that a
Deckobject is the right way to represent hands and piles. We might want new classes for other collections of cards.
We can solve the first problem by replacing the
Card array with an
ArrayList, which is in the
java.util package. An
ArrayList is a collection, which is an object that contains other objects.
The Java library provides a variety of collections. For our purposes,
ArrayList is a good choice because it provides methods to add and remove elements, and it grows and shrinks automatically.
To solve the second problem, we can use a language feature called inheritance. We’ll define a new class,
CardCollection, to represent a collection of cards. Then we’ll define
Hand as subclasses of
A subclass is a new class that “extends” an existing class; that is, it has the attributes and methods of the existing class, plus more. We’ll see the details soon, but let’s start with