java - Should I instantiate instance variables on declaration or in the constructor? -


is there advantage either approach?

example 1:

class {     b b = new b(); } 

example 2:

class {     b b;      a() {          b = new b();     } } 

  • there no difference - instance variable initialization put in constructor(s) compiler.
  • the first variant more readable.
  • you can't have exception handling first variant.
  • there additionally initialization block, put in constructor(s) compiler:

    {     = new a(); } 

check sun's explanation , advice

from this tutorial:

field declarations, however, not part of method, cannot executed statements are. instead, java compiler generates instance-field initialization code automatically , puts in constructor or constructors class. initialization code inserted constructor in order appears in source code, means field initializer can use initial values of fields declared before it.

additionally, might want lazily initialize field. in cases when initializing field expensive operation, may initialize needed:

expensiveobject o;  public expensiveobject getexpensiveobject() {     if (o == null) {         o = new expensiveobject();     }     return o; } 

and (as pointed out bill), sake of dependency management, better avoid using new operator anywhere within class. instead, using dependency injection preferable - i.e. letting else (another class/framework) instantiate , inject dependencies in class.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -