简体   繁体   中英

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.

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

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

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