>没有区别 – 实例变量初始化实际上是由编译器放在构造函数中。
>第一个变体更易读。
>您不能使用第一个变量进行异常处理。
>还有一个初始化块,它也是由编译器放在构造函数中:
{
a = new A();
}
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.
此外,您可能需要延迟初始化字段。在初始化字段是昂贵的操作的情况下,您可以在需要时立即初始化它:
ExpensiveObject o;
public ExpensiveObject getExpensiveObject() {
if (o == null) {
o = new ExpensiveObject();
}
return o;
}
最终(如Bill所指出的),为了依赖管理,最好避免在类中的任何地方使用新运算符。相反,使用Dependency Injection是更好的 – 即让别人(另一个类/框架)实例化和注入类中的依赖。