Search code examples
javajavafxstack-overflow

java.lang.StackOverflowError but i'm not looping anything


I have two methods one in the main class and one in a class called 'DeleteWall' .I'm creating instances of each class so I can access their methods .I've read all the posts on stackOverflows but I don't see what i'm doing wrong ...like i'm not looping it to make a new instance as far as I can see anyway.I'll highlight the lines which are causing the errors as intellij says.I'm only calling demo once aswell .Oh and the method 'delNode' is in the main class hence the instance of it 'werk'.

    //Main class
    DeleteWall ok=new DeleteWall(); //error line
    public void demo(){
    System.out.println("running");
    ok.delWalls(30,0,30,30);
    System.out.println("didnt stop");
    }
     //DeleteWall class
     public class DeleteWall  {

     Main werk = new Main(); //error line

     public  void delWalls(int Sx, int Sy, int Ex, int Ey) {


     werk.delNode(Sx, Sy, Ex, Ey);
     }

     }

the error enter image description here


Solution

  • The main problem is reduced to

    public class Main {
        DeleteWall ok = new DeleteWall();
    }
    

    and

    public class DeleteWall  {
        Main werk = new Main();
    }
    

    if any of these class gets instantiated, an instance of the other must be created which in turn will again create a new instance of first, and so on. The whole design is strange, like declaring that each House always contains a Car and each Car always contains a House.

    Solving the problem: have the DeleteWall receive the instance of Main instead of creating a new one. Some possibilities:

    • in the constructor

      public class Main {
          DeleteWall ok = new DeleteWall(this);
      }
      
      ////
      
      public class DeleteWall  {
          Main werk;
          public DeleteWall(Main main) {
              werk = main;
          }
      }
      
    • when calling

      public class Main {
          DeleteWall ok = new DeleteWall();
          public void demo() {
              ok.delWalls(this, 30, 0, 30, 30);
          }
      }
      
      ////
      
      public class DeleteWall  {
          public void delWalls(Main werk, ...) {
              werk.delNodes(...);
          }
      }
      

    (there are many other possibilities, it depends heavily on what the program should do, how the problem is modeled, preferences, ...)