3

While running this code it shows Stackoverflow error. What is it I am doing wrong, why does the code compile?

public class Foo {
    int a = 5;
    Foo f = new Foo();

    void go() {
        System.out.println(f.a);
    }

    public static void main(String[] args) {
        Foo f2 = new Foo();
        f2.go();
    }
}
2
  • The stack trace should probably tell you. Commented Feb 3, 2012 at 9:23
  • Object orientated view: a Foo that contains a Foo that contains a Foo that contains a Foo that contains a ... Commented Feb 3, 2012 at 10:29

5 Answers 5

7
Foo f=new Foo();

You create an instance of Foo, with a variable which itself is an instance of Foo, and initialize it in the constructor.

This causes infinite recursion of constructor invokations, untill your stack is out of space.

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

Comments

4

It's your f initializer:

public class Foo {
    int a=5;
    Foo f=new Foo();

Whenever a new Foo is constructed, as part of it's initialization, it attempts to create a Foo and assign it to f. But obviously, constructing that Foo starts the whole process again.

Comments

3

When your program execution starts, control enters to the main method, and finds Foo f2=new Foo(). It creates object of Foo and while creating object it has to instantiate all its instance variables which includes Foo f=new Foo(), so it again creates a new Foo object and loads all instance variables in that and there also it finds same Foo f=new Foo(), so it again creates the Foo object and this will continue until the stack is overflowed.

This can be solved just by changing Foo f=new Foo(); to Foo f=null;

Comments

1

You can call go method with an instance only. so before call to go started, c'tor has run for class Foo

Now, C'tor is designed to initialize all instance members.

So one by one it initializes:

a is initialized to 5

f is initialized to an Object // but here is the catch, f never gets initilized.

before = operator works, C'tor is called and thus the chain continues.

If you see the stacktrace, it'll have init written in it. so it's failing during initialization only.

Comments

1

This is basically a repost of your question from an hour ago. Please take the time to understand the answers people give you.

Your code is the same as:

public class Foo {
    Foo f = null;

    public Foo() {
        this.f = new Foo(); // recursion here
    }

    //do your other stuff

}

}

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.