简体   繁体   中英

Loading data in constructors and not in constructors

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

}

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.

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...

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.

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 .

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM