Skip to main content
Engineering LibreTexts

5.4: Dealing Cards

  • Page ID
  • At this point we can create a Deck and start dealing cards. Here’s a simple example that deals five cards to a hand, and deals the rest into a draw pile:

    Deck deck = new Deck("Deck");
    Hand hand = new Hand("Hand");, 5);
    Hand drawPile = new Hand("Draw Pile");
    System.out.printf("Draw Pile has %d cards.\n",

    CardCollection provides dealAll, which deals all of the remaining cards. Here’s the output of the previous example:

    5 of Diamonds
    Ace of Hearts
    6 of Clubs
    6 of Diamonds
    2 of Clubs
    Draw Pile has 47 cards. 

    Of course, if you run this example you will probably get a different hand, because the deck is shuffled randomly.

    If you are a careful reader, you might notice something strange about this example. Take another look at the definition of deal:

    public void deal(CardCollection that, int n) {
        for (int i = 0; i < n; i++) {
            Card card = popCard();

    Notice that the first parameter is supposed to be a CardCollection. But we invoked it like this:

    Hand hand = new Hand("Hand");, 5); 

    The argument is a Hand, not a CardCollection. So why is this example legal? It’s because Hand is a subclass of CardCollection, so a Hand object is also considered to be a CardCollection object. If a method expects a CardCollection, you can give it a Hand, a Deck, or a CardCollection.

    But it doesn’t work the other way around: not every CardCollection is a Hand, so if a method expects a Hand, you have to give it a Hand, not a CardCollection.

    If it seems strange that an object can belong to more than one type, remember that this happens in real life, too. Every cat is also a mammal, and every mammal is also an animal. But not every animal is a mammal, and not every mammal is a cat.

    • Was this article helpful?