Take a look at
StackOverflowError (Java Platform SE 7 ) to see why might this error occur. (Note, "stack" in the API doc refers to JVM internals.)
The StackOverflowError is many ways is similar to the problem discussed in another thread. My reply there,
http://www.javaprogrammingforums.com...tml#post146642, is also applicable to your case, especially this part:
Originally Posted by
jashburn
Note that when a class is instantiated, the new object is initialised by going through the following procedure (on a high-level):
- invoke another constructor in the same class (if such a call exists)
- invoke a superclass constructor
- execute instance initialisers and instance variable initialisers
- execute the rest of the body of the constructor
(See
Object initialization in Java | JavaWorld and
Chapter*12.*Execution for elaboration on the above.)
In your case, it is at step #4 above. Consider the following, based on the code in your post but significantly simplified:
public class ArrayStack {
ArrayStack arrayStack;
ArrayStack() {
arrayStack = new ArrayStack();
}
public static void main(String[] args) {
ArrayStack myStack = new ArrayStack();
}
}
When "
ArrayStack myStack = new ArrayStack()" is called in the
main method, it goes through the object initialisation procedure. On reaching step #4, it executes the constructor,
ArrayStack(). The body of the constructor contains "
arrayStack = new ArrayStack()," i.e., code to instantiate and initialise another
ArrayStack object. This again, goes through the object initialisation procedure, execute the constructor, etc.,
ad infinitum.
In short, you cannot instantiate the same object in the object's class constructor as it causes infinite recursion.