coderaider
coderaider

Reputation: 141

stackoverflow error when creating object outside the main method

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();
    }
}

Upvotes: 3

Views: 2498

Answers (5)

Chandra Sekhar
Chandra Sekhar

Reputation: 19492

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;

Upvotes: 3

Azodious
Azodious

Reputation: 13872

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.

Upvotes: 1

Mike Adler
Mike Adler

Reputation: 1200

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

}

}

Upvotes: 1

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239646

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.

Upvotes: 4

amit
amit

Reputation: 178431

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.

Upvotes: 7

Related Questions