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

前端 未结 15 2027

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

    I think Example 2 is preferable. I think the best practice is to declare outside the constructor and initialize in the constructor.

提交回复
热议问题