I just realized I've been initializing instance variables in the following way:
public class Service{
private Resource resource;
public Service(){
resource = new Resource();
//other stuff...
}
}
...out of just being used to it, I guess.
I was wondering if this leads to any differences in instantiation, compilation, or anything I'm not realizing about, with the following way of doing it:
public class Service{
private Resource resource = new Resource();
public Service(){
//other stuff...
}
}
I do realize that there's an advantage in the first way of doing it in case you might want different "default" values, as in the following case:
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...
}
}
vs
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...
}
}
...since the latter one makes instances of the variables that will get trashed if the parameterized constructor is called, but this is a more "complex" case and probably the reason I got used to the former way of initializing instances.
Are there any advantages about either way aside from getting used to one of them for when it really counts?