我刚刚意识到我一直在用以下方式初始化实例变量:
public class Service{
private Resource resource;
public Service(){
resource = new Resource();
//other stuff...
}
}
我想知道这是否会导致实例化、编译或任何我没有意识到的方面的任何差异,方法如下:
public class Service{
private Resource resource = new Resource();
public Service(){
//other stuff...
}
}
我确实意识到,如果您可能需要不同的“默认”值,那么第一种方法有一个优势,如下例所示:
public class Foo{
private String bar;
private SomeClass bar2;
public Foo(){
bar = "";
bar2 = new SomeClass();
//other stuff...
}
public Foo(String bar, SomeClass bar2){
this.bar = bar;
this.bar2 = bar2;
//other stuff...
}
}
public class Foo{
private String bar = "";
private SomeClass bar2 = new SomeClass();
public Foo(){
//other stuff...
}
public Foo(String bar, SomeClass bar2){
this.bar = bar;
this.bar2 = bar2;
//other stuff...
}
}
…因为后一种方法生成变量的实例,如果调用参数化构造函数,这些变量的实例将被丢弃,但这是一种更“复杂”的情况,可能也是我习惯于前一种方法初始化实例的原因。
在真正重要的时候,除了习惯其中一种方法之外,这两种方法还有什么好处吗?