Search code examples
javastack-overflow

StackOverflowError when creating an object of another class


I am working on a game for the past month or so and no matter what I do, I almost always get a StackOverflowError. This is what it says in the trace :

Exception in thread "main" java.lang.StackOverflowError
at retroscroller.Player.<init>
at retroscroller.Hole.<init>

The error occurs at these lines : (Player Class)

Hole hl = new Hole();

(In the hole class):

Player ch = new Player();

Do I get the error because both classes are extending each other and both are superclasses ?


Solution

  • In most of the cases this indicates infinite recursion. Check if you are doing something of the form A calling B calling A calling B calling A ... where A and B are some methods/constructors. If so, restructure your code to eliminate this.