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

前端 未结 15 2047

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:02

    It's quite different actually:

    The declaration happens before construction. So say if one has initialized the variable (b in this case) at both the places, the constructor's initialization will replace the one done at the class level.

    So declare variables at the class level, initialize them in the constructor.

提交回复
热议问题