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

前端 未结 15 2037

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

    The second option is preferable as allows to use different logic in ctors for class instantiation and use ctors chaining. E.g.

    class A {
        int b;
    
        // secondary ctor
        A(String b) {
             this(Integer.valueOf(b));
        }
    
        // primary ctor
        A(int b) {
             this.b = b;
        }
    }
    

    So the second options is more flexible.

提交回复
热议问题