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");
    }
}
                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
each new test() is creating another test item2 = new test(); getting into an infinite recursion (stackoverflowerror)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With