Search code examples
javaoopcompiler-errorsstack-overflow

I'm getting a StackOverflowError that recursively calls the same error


I'm not sure what is wrong with my program. Essentially I just want to make an object of my class. Then that object should create another object inside its constructor. But when I create the object from inside of the first object's constructor, I get the error:

"Exception in thread "main" java.lang.StackOverflowError at Setup.(Setup.java:31) at GameController.(GameController.java:30)"

This section of the error repeats until my runtime 'error' box is full:

"at Setup.(Setup.java:31)
at GameController.(GameController.java:30)"

Here is my code: (Object that is created in main)

public class GameController {
GameController() {   
Setup Set = new Setup(); //Refers to error happening here.

(Set Object Class)

public class Setup extends GameController {
Setup() { //Refers to error happening here.

I don't mind doing my code differently but I'd like to know what I'm doing wrong so I can do it right in the future.


Solution

  • Don't have Setup extend GameController! This is what's causing the unwanted recursion and is likely not necessary.

    When you create a Setup object, it calls GameController's constructor, which creates a Setup object which then calls GameController's constructor, which creates a Setup object which then calls GameController's constructor, which creates a Setup object which then calls GameController's constructor, which creates a Setup object which then calls GameController's constructor, which creates a Setup object which then calls GameController's constructor, which creates a Setup object which then calls ....

    ad infinitum.

    I suspect that you're using inheritance for inappropriate reasons here, and so again, simply don't have Setup extend GameController and this problem should be fixed.


    Regarding,

    Oh, and it does NOT compile.

    Impossible. If it didn't compile and run, you couldn't see this exception.