I’m getting an error:
Exception in thread "main" java.lang.StackOverflowError
at CreateCardDeck.<init>(CreateCardDeck.java:6)
at CardStack.<init>(CardStack.java:7)
at CreateCardDeck.<init>(CreateCardDeck.java:8)
at CardStack.<init>(CardStack.java:7)
at CreateCardDeck.<init>(CreateCardDeck.java:8)
...
...
...
at CardStack.<init>(CardStack.java:7)
at CreateCardDeck.<init>(CreateCardDeck.java:8)
But I don’t understand why there would be an error. In my code I have specified amount of cards etc. So what would be the problem here?
public class CreateCardDeck
{
int deckSize = 52;
CardStack cardStack;
CreateCardDeck()
{
cardStack = new CardStack(deckSize); --------------- problem here -----
}
}
And
class CardStack extends CreateCardDeck
{
public CardStack(int s) ------------ problem here --------------
{
maxSize = s;
stackArray = new Card[maxSize];
top = -1;
}
......
}
You’re using recursion inadvertently by having CardStack extend CreateCardStack. Don’t use inheritance here. Besides causing your StackOverflowError error, it’s just plain wrong. CardStack is not a more specialized version of CreateCardStack and so should not extend it. In fact CardStack should have no knowledge about CreateCardStack at all.
Your recursion and SO error:
Your CardStack constructor will by default call the super’s constructor which creates an other CardStack object whose constructor will by default call the super’s constructor which creates an other CardStack object whose constructor will by default call the super’s constructor which creates an other CardStack object whose constructor will by default call the super’s constructor which creates an other CardStack object whose constructor will by default call the super’s constructor which creates an other CardStack object whose constructor ….. almost ad infinitum until memory runs out.