DonX DonX - 5 months ago 14
Java Question

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

Is there any advantage for either approach?

Example 1:

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


Example 2:

class A {
B b;

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

Answer
  • there is no difference - the instance variable initialization is actually put in the constructor(s) by the compiler
  • the first variant is more readable
  • you can't have exception handling with the first variant
  • there is additionally the initialization block, which is as well put in the constructor(s) by the compiler:

    {
        a = new A();
    }
    

Check Sun's explanation and advice

From this tutorial:

Field declarations, however, are not part of any method, so they cannot be executed as statements are. Instead, the Java compiler generates instance-field initialization code automatically and puts it in the constructor or constructors for the class. The initialization code is inserted into a constructor in the order it appears in the source code, which means that a field initializer can use the initial values of fields declared before it.

Additionally, you might want to lazily initialize your field. In cases when initializing a field is an expensive operation, you may initialize it as soon as it is needed:

ExpensiveObject o;

public ExpensiveObject getExpensiveObject() {
    if (o == null) {
        o = new ExpensiveObject();
    }
    return o;
}

And ultimately (as pointed out by Bill), for the sake of dependency management, it is better to avoid using the new operator anywhere within your class. Instead, using Dependency Injection is preferable - i.e. letting someone else (another class/framework) instantiate and inject the dependencies in your class.

Comments