Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java class member initialisation

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.

like image 404
David Avatar asked Sep 17 '10 13:09

David


2 Answers

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

like image 198
jmj Avatar answered Sep 20 '22 11:09

jmj


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

like image 31
Bozho Avatar answered Sep 17 '22 11:09

Bozho