views:

75

answers:

2

Hello SO,
I am a bit ashamed to ask that, being a Java programmer for years, but here goes:
Is there a difference between allocating objects during construction, and doing so directly when declaring the relevant field? That is, is there a difference between the following two:

public class MyClass{
    MyObj obj=new MyObj();
}

AND

public class MyClass{
    MyObj obj;
    public MyClass() {
        obj=new MyObj();
    }
}

Of course, I assume this specific init's do not rely on outside parameters.

+2  A: 

instance variable initialization done before constructor call

Its not good to do.
You can restrict user from call of const. if you want to perform certain operation before initialization.

Best Practice:

  1. Don't initialize with the default values in declaration (null, false, 0, 0.0...).
  2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
  3. If the value of the field changes because of a constructor parameter put the >initialization in the constructors.
  4. Be consistent in your practice. (the most important rule)

from here

org.life.java
Also with static variable/method calls you can generate a NullPointerException if the variable is not initialized until the constructor.
Sean
I would dispute that *any* of those rules is "best practice". None of them significantly effect code readability, and that's the only thing that really matters here.
Stephen C
Code readibility is not only concern i think, I feel it is best for me atleast. and ofcourse any of the java programmer will go for const. first to read the code.
org.life.java
+2  A: 

No, there isn't. Except that if you add multiple constructors you'll have duplicate code.

An alternative is to use an initializer block

{
   var = 1;
}

Reference: Initializing Fields

Bozho