5

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");
    }
}
2
  • 2
    It seems quite logical that stack overflow error lead to a post on Stack Overflow. Commented Nov 29, 2013 at 18:54
  • @skuntsel pretty easy to find the right SE to post on in this case! Commented Nov 29, 2013 at 18:58

5 Answers 5

7

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

It's not an infinite loop
1

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.

Comments

1

Because whenever a new instance gets initialized of your test class, the declared test item2 = new test(); in your class context tries to create another instance which will again result in creating another instance with continuous call of constructor function. JAVA uses stack to hold local variables and partial results which plays a part in method invocation and return. hence the stack is eventually overflowed.

Comments

1

break your Question into smaller unit for better understanding, Below lines are enough to give you StackOverflow.

class test {
    test item2 = new test();   //LINE 1

    public static void main(String[] args) {
        test item = new test();  //LINE 2
    }
}

Line 2 is Entry point, as soon it executes "new test()" of line 2, it will try to create one object of type test which has one variable with name "item2"(from line 1) but to initialize a reference item2 it has to create new object of type test, which is repetitive process.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.