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

前端 未结 15 2028

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

    I've not seen the following in the replies:

    A possible advantage of having the initialisation at the time of declaration might be with nowadays IDE's where you can very easily jump to the declaration of a variable (mostly Ctrl--) from anywhere in your code. You then immediately see the value of that variable. Otherwise, you have to "search" for the place where the initialisation is done (mostly: constructor).

    This advantage is of course secondary to all other logical reasonings, but for some people that "feature" might be more important.

提交回复
热议问题