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

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

Code 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 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; } [...] } 
+6
source share
4 answers
  public class Deck <T extends Card> 

The deck does not expand the Card.

This is a general annotation, and it says that the deck can be of type T, where T is a subclass of Card.

This is the same as the Java collection classes, where 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 
+16
source

Class classes do not extend Map. It contains an ArrayList map.

The designation <T extends Card> bit confusing, but this means that this deck is "parameterized" by T, which should expand (be a subclass of) Maps. Thus, it can be Pinochle cards, bridge cards, tarot cards, etc., for example.

 Deck myTarot = new Deck<TarotCard>(); 
+2
source

You have interpreted this incorrectly. You should read the Deck of T class (which extends the Map). So you have a List<Something> (a list of something), which you have here is a Deck<Cards> (deck of cards). It could also be a Deck<PokerCard> if PokerCard extends a card

0
source

A class extends another class when it wants to inherit the properties of this class. eg,

 Class A{ public void show() { //something to show } } Class B extends A{ //B can now enjoy the show() function defined by A } 

Here's how inheritance works.

The cat will expand the Animal, because cat is a subset of the animal, it can fall into this category.

Here, Deck does not expand the map.

0
source

Source: https://habr.com/ru/post/913998/


All Articles