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

前端 未结 15 2148

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

    Using either dependency injection or lazy initialization is always preferable, as already explained thoroughly in other answers.

    When you don't want or can't use those patterns, and for primitive data types, there are three compelling reasons that I can think of why it's preferable to initialize the class attributes outside the constructor:

    1. avoided repetition = if you have more than one constructor, or when you will need to add more, you won't have to repeat the initialization over and over in all the constructors bodies;
    2. improved readability = you can easily tell with a glance which variables will have to be initialized from outside the class;
    3. reduced lines of code = for every initialization done at the declaration there will be a line less in the constructor.

提交回复
热议问题