In some Java code, why does the class Deck extend the Card class?
-
03-06-2021 - |
Question
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;
}
[...]
}
Solution
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
OTHER TIPS
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>();
A class extends another class when it wants to inherit properties of that class. for eg.
Class A{
public void show()
{
//something to show
}
}
Class B extends A{
//B can now enjoy the show() function defined by A
}
This is how inheritance work.
Cat will extend Animal because, cat is a subset of animal, it can come under that category.
Here Deck does not extend card.
You interpreted it the wrong way. You should read class Deck of T (which extends Card). Like so you have an List<Something>
(list of something) you have here Deck<Cards>
(a deck of cards). That could be also a Deck<PokerCard>
, if PokerCard extends Card