-2

Why Stack overflow error occurs on creating nonstatic instance within an instance of same class ??

public class ObjectTest {
    ObjectTest instanceObj = new ObjectTest("Outside");

    public ObjectTest(String s) {
        System.out.println(s);
    }

    public static void main(String[] args) {
        ObjectTest localObj = new ObjectTest("Inside");
    }
}

But the problem gets resolved by below modification :

static ObjectTest instanceObj = new ObjectTest("Outside");

It is understood like circular dependency occurs in first case while assigning new object to instanceObj reference

Can anyone clarify the whole thing ?? Why for static reference circular dependency doesnot occur??

1
  • Thanks everyone...Though i was aware of static/nonstatic concept.. but now i clearly understood ...I was bit confused..Thankss again !! Commented Mar 26, 2013 at 18:49

3 Answers 3

6

When instanceObj is non-static, the constructor for the ObjectTest creates another ObjectTest which creates another ObjectTest, and so on ad infinitum. When it's static, only one instanceObj is created for the entire ObjectTest class ... it is static, after all. :) When instanceObj is static and its ObjectTest is created, it already has the static instanceObj, which is itself. It does take some getting used to, it might help to work it out on paper and make sure you're clear what the static keyword means.

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

Comments

2

Because it creates object inside object and again object inside the object. This is like infinite mirror image when two Mirror keep in front of each other.

About static object, it is not instance of the class. static object is created at the class level.

We use such static object of the same class while designing SingleTon class.

Comments

1

Because the code you exposed is almost the same as:

public class ObjectTest {
    ObjectTest instanceObj;

    public ObjectTest(String s) {
        instanceObj = new ObjectTest("Outside"); // creating another object executing this constructor again
        System.out.println(s);
    }

    public static void main(String[] args) {
        ObjectTest localObj = new ObjectTest("Inside");
    }

}

When you modify the field to static field you do something like:

public class ObjectTest {
    static ObjectTest instanceObj;

    static {
        instanceObj = new ObjectTest("Outside");
    }    

    public ObjectTest(String s) {
        System.out.println(s);
    }

    public static void main(String[] args) {
        ObjectTest localObj = new ObjectTest("Inside");
    }

}

executing the constructor just once.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.