views:

64

answers:

4

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();
   }
}
+3  A: 
erickson
+6  A: 

You call the constructor to create a new instance of your object. It has a reference to another instance, which you initialize with another new instance of ObjectType which, in turn, does the same thing. it's an infinite number of calls until you get that error.

This will work.

public class ObjectTest { 

  public ObjectTest() { 

   } 


  public static void main(String[] args) { 

     ObjectTest localObj = new ObjectTest(); 
   } 
} 
duffymo
+1  A: 

Because you are recursively creating yourself.

You need to inject your instance, or have some other class manage that property.

public class ObjectTest {

 public ObjectTest() {
    instanceObj  = null;
 }
 public ObjectTest(ObjectTest myObjectTest) {
     instanceObj = myObjectTest;
 }
}
Nix
+2  A: 

Let's see what will be executed :

  1. main() create a new instance of ObjectTest
  2. the ObjectTest class has a field instanceObj which will contain an ObjectTest
  3. the instanceObj in initialized with a new ObjectTest
  4. go to step 2

I think you wanted something more like this :

public class ObjectTest {
    private static ObjectTest instanceObj;

    private ObjectTest() {
    }

    public static ObjectTest getInstance() {
        if (instanceObj != null) {
            instanceObj = new ObjectTest();
        }
        return instanceObj;
    }

    public static void main(String[] args) {

        ObjectTest localObj = ObjectTest.getInstance();
    }
}

Or this :

public class ObjectTest {
    private static final ObjectTest instanceObj = new ObjectTest();

    private ObjectTest() {
    }

    public static ObjectTest getInstance() {
        return instanceObj;
    }

    public static void main(String[] args) {

        ObjectTest localObj = ObjectTest.getInstance();
    }
}

This is the Singleton pattern.


On the same topic :

Colin Hebert