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

前端 未结 15 2038

Is there any advantage for either approach?

Example 1:

class A {
    B b = new B();
}

Example 2:

class A {
    B b;         


        
15条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 07:01

    Both of the methods are acceptable. Note that in the latter case b=new B() may not get initialized if there is another constructor present. Think of initializer code outside constructor as a common constructor and the code is executed.

提交回复
热议问题