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

前端 未结 15 1841

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

    I take it is almost just a matter of taste, as long as initialization is simple and doesn't need any logic.

    The constructor approach is a bit more fragile if you don't use an initializer block, because if you later on add a second constructor and forget to initialize b there, you'll get a null b only when using that last constructor.

    See http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html for more details about initialization in Java (and for explanations on initalizer blocks and other not well known initialization features).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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-<hover_over_the_variable>-<left_mouse_click>) 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.

    0 讨论(0)
提交回复
热议问题