views:

118

answers:

6

I just want to know the difference between loading the data inside the constructor and loading the data outside the constructor but not inside any methods

example: Loading inside constructor

public class Model{
   Object testobject;

   public Model(){
      testobject=new Object();
   }

}

VS

example: Loading outside constructor

public class Model{
   Object testobject=new Object();

   public Model(){
   }

}
+4  A: 

The only difference is when you have multiple constructors it can be tedious to write...

testObject = new Object();

in every single one. However if you decided you want...

public Model(Object otherObject) {
    testObject = otherObject;
}

You would be doing slightly more work if you declared it twice.

Pace
+1  A: 

There is no (real) difference on byte code level. It's more a question of coding style.

Bozho gave a good answer on similar question here.

Andreas_D
+3  A: 

There is in fact one small difference (but probably too obvious to notice). The automatic initialization (outside constructor as you call it) is executed before the constructor. Just a matter of execution order...

Koen
+1  A: 

They are basically the same. Initialization in the declaration: a slight advantage is that you don't have to worry about multiple constructors. On the other hand, you have a little less flexibility, specially if you need some logic or exception handling.

http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html

leonbloy
+1  A: 

Field initialization happens before the lines in the constructor are executed. You can see this if you run your program in a debugger and step into the constructor for Model.

Here's a couple of links discussing when statics, static blocks, fields, member initialization blocks, and constructors are called:

Gray
+3  A: 

It affects order of initialization. The initializer is executed before the body of the constructor. In a simple case like your example this is not important, but in more complex code it might be.

Another difference is that you can handle exceptions inside the constructor if necessary.

Dave Costa
The execution order is a difference, but I don't think it may matter. I feel, if you get different results by moving this, you're probably writing bad code. Do you have any real life experience with code where it actually matters for a good reason?
Koen
@Koen - No, and I wasn't trying to say that I do. I just wanted to point out that it is possible for the execution order to be significant. People do write bad code.
Dave Costa