Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In some Java code, why does the class Deck extend the Card class?

I am reading some code in Java, which I am not familiar with, but it seems weird that if a class is Deck (for a deck of cards), it already has an instance variable of an array of Cards, so why does Deck extend or inherit Card? I thought class A inherits class B only if A is a B (Cat inherits Animal because a cat is an animal).

The code is below:

public class Deck <T extends Card> {
    private ArrayList<T> cards;
    private int dealtIndex = 0; // marks first undealt card

    public Deck() {
    }

    public void setDeckOfCards(ArrayList<T> deckOfCards) {
        cards = deckOfCards;
    }

    public void shuffle() {
        for (int i = 0; i < cards.size(); i++) {

    [...]
}

public abstract class Card {
    private boolean available = true;

    /* number or face that's on card - a number 2 through 10, 
     * or 11 for Jack, 12 for Queen, 13 for King, or 1 for Ace 
     */
    protected int faceValue;
    protected Suit suit;

    public Card(int c, Suit s) {
        faceValue = c;
        suit = s;
    }

    public abstract int value();

    public Suit suit() { 
        return suit; 
    }

    [...]

}
like image 852
Jeremy L Avatar asked Apr 24 '12 03:04

Jeremy L


2 Answers

 public class Deck <T extends Card> 

Deck does not extend Card.

This is a generic type annotation, and it says that a Deck can be of type T where T is a subclass of Card.

This is the same as Java's collection classes, where a List of String also does not extend String (but contains String instances).

This allows you to write code like:

Deck<PokerCard> pokerDeck = new Deck<PokerCard>();

PokerCard c = pokerDeck.getTopCard();   
// now you know it is a PokerCard, not just any old card

pokerDeck.insert(new MagicTheGatheringCard()); 
// get a compile error for wrong card type
like image 127
Thilo Avatar answered Nov 14 '22 21:11

Thilo


The class deck does not extend Card. It contains contains an ArrayList of Cards.

The <T extends Card> notation is a little confusing, but it means that this Deck is "parametized" by T, which must extend, (be a subclass of) Cards. So it could be Pinochle Cards, Bridge Cards, Tarot Cards etc... e.g.

Deck myTarot = new Deck<TarotCard>();
like image 42
user949300 Avatar answered Nov 14 '22 20:11

user949300