eMRe
eMRe

Reputation: 3247

Extending class, implicit super constructor is undefined error

I am using Java. I have got 2 classes

class Card
class Deck extends Card

I get a constructor error.

I have to make a blackjack game for college and Deck class has to be extended.

What can I do to solve this problem?

class Card
{
    int rank, suit;
    String[] suits = { "hearts", "spades", "diamonds", "clubs" };
    String[] ranks  = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };

    Card(int suit, int rank)
    {
        this.rank=rank;
        this.suit=suit;
    }

    String toString()
    {
          return ranks[rank] + " of " + suits[suit];
    }

    int getRank() {
         return rank;
    }

    int getSuit() {
        return suit;
    }
}




class Deck extends Card{

    ArrayList <Card> cards;
    int numberdeck;
    Deck()
    {
        cards = new ArrayList<Card>();
        for (int a=0; a<=3; a++)
        {
            for (int b=0; b<=12; b++)
            {
                cards.add( new Card(a,b) );
            }
        }
    }

    Card drawFromDeck()
    {
        Random generator = new Random();
        int index= generator.nextInt( cards.size() );
        return cards.remove(index);
    }

    int getTotalCards()
    {
        return cards.size();
    }
}

Upvotes: 0

Views: 1028

Answers (2)

John Kugelman
John Kugelman

Reputation: 361595

Deck really ought not extend Card. Sub-classing encodes an is-a relationship. A lion is an animal, so Lion extends Animal. You can tell that sub-classing is inappropriate because the getRank() and getSuit() methods make no sense on an entire deck of cards.

A deck of cards is not a card; a deck contains other cards. The contains relationship is already represented by the ArrayList <Card> cards array.

Upvotes: 2

reprogrammer
reprogrammer

Reputation: 14718

The constructor in the subclass is supposed to invoke the corresponding constructor in the super class, but, such a constructor is not found in your code.

Either add a constructor that takes no argument to the superclass or make the constructor in the subclass invoke the constructor in the superclass.

You can invoke the constructor of the superclass using super(0, 0); at the beginning of the body of the constructor of the subclass.

Upvotes: 3

Related Questions