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

前端 未结 15 2149

Is there any advantage for either approach?

Example 1:

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

Example 2:

class A {
    B b;         


        
15条回答
  •  猫巷女王i
    2020-11-22 07:02

    The second is an example of lazy initialization. First one is more simple initialization, they are essentially same.

提交回复
热议问题