Search code examples
javastack-overflow

why does this object cause a stack overflow?


I'm not exactly sure why this causes a stack overflow. I know if I call the someMethod method without the instance it works fine, but I'd like to know why. Thanks

class test {
    public static void main(String[] args) {
        test item = new test();
        item.someOtherMethod();
    }

    test item2 = new test();

    void someOtherMethod() {
        item2.someMethod();
    }

    void someMethod() {
      System.out.println("print this");
    }
}

Solution

  • test item2 = new test();

    This is an instance variable in your class test. When you make an instance of test, it will make a new instance of test and assign to to item2. But that test has to make a test and assign it to it's item2 and so on... You get infinite recursion, so you will get a stack overflow for any stack very quickly