Hi can anybody please explain me why is this code snippet giving me StackOverflowError
I really appreciate if you can explain what is happening when instanceObj initializing and calling ObjectTest constructor and java.lang.Object constructor. It seems to me ObjectTest constructor loop over and over.But I don’t know exact reason? So any suggestion…
public class ObjectTest {
public ObjectTest() {
}
ObjectTest instanceObj = new ObjectTest();
public static void main(String[] args) {
ObjectTest localObj = new ObjectTest();
}
}
Let’s see what will be executed :
main()create a new instance ofObjectTestObjectTestclass has a fieldinstanceObjwhich will contain anObjectTestinstanceObjin initialized with a newObjectTestI think you wanted something more like this :
Or this :
This is the Singleton pattern.
On the same topic :