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

前端 未结 15 1839

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).

提交回复
热议问题