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

前端 未结 15 1888

Is there any advantage for either approach?

Example 1:

class A {
    B b = new B();
}

Example 2:

class A {
    B b;         


        
15条回答
  •  旧时难觅i
    2020-11-22 07:02

        class MyClass extends FooClass {
        String a = null;
    
        public MyClass() {
            super();     // Superclass calls init();
        }
    
        @Override
        protected void init() {
            super.init();
            if (something)
                a = getStringYadaYada();
        }
    }
    

    Regarding the above,

    String a = null;
    

    null init could be avoided since anyway it's the default. However, if you were to need another default value, then, because of the uncontrolled initialization order, I would fix as follow:

    class MyClass extends FooClass 
    {
        String a;
        {
            if( a==null ) a="my custom default value";
        }
        ...
    

提交回复
热议问题