简体   繁体   中英

private final Card[]cards, how do I use this in another class

Private final Card[] cards;
Public Deck() {
    this.cards = new Card[52];
    int i = 0;
    for (Suit suit : Suit.values()) {
        for (Rank rank : Rank.values()) {
            cards[i++] = new Card(rank, suit);
        }
    }
}

This is an array of cards it works in the class it is made called Deck. I am trying to make a card game that implements this along with other classes. I want the Deck class to be reusable so it works in any card game. I want a Deck of cards essentially. Now I know it works because I can use the printDeck() method I have in the same class to print off a deck of cards but don't know how or even if I can call it in a card game. Why would I need a getter when the new operator creates an instance of Deck which is essentially an array of Card [52] cards? I want this Deck to be reusable so I don't have to rewrite it for every different type of card game.

You can simply define a getter method in your Deck class as below :

public Card[] getCards() {
   return cards;
}

Them from another class you can use this getter method once you have a Deck object :

Card[] cards = yourDeckObject.getCards();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM