Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
    }
}
like image 529
user3050397 Avatar asked Nov 29 '13 18:11

user3050397


3 Answers

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

like image 195
Cruncher Avatar answered Oct 29 '22 21:10

Cruncher


each new test() is creating another test item2 = new test(); getting into an infinite recursion (stackoverflowerror)

like image 38
Liviu Stirb Avatar answered Oct 29 '22 21:10

Liviu Stirb


You have defined the class test such that every instance of the class test contains a new instance of the class test. It is a classic case of infinite recursion, thus a rapid path to a stack overflow.

like image 20
ZachOfAllTrades Avatar answered Oct 29 '22 21:10

ZachOfAllTrades