Reputation: 6480
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;
}
......
}
Upvotes: 1
Views: 640
Reputation: 6668
CardStack inherits from CreateCardDeck. CreateCardDeck's constructor instantiates a CardStack, which causes CreateCardDeck's constructor to be called again, and so on infinitely.
I suggest rearranging and redesigning your code. CreateCardDeck looks like the name for a method (because it starts with a verb). Maybe what you want is actually a static method in CardStack called createCardDeck.
Upvotes: 1
Reputation: 285405
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.
Upvotes: 7