0

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?

Nicolás Marzano
  • 161
  • 2
  • 14
  • You can probably find an answer here: https://stackoverflow.com/questions/4916735/default-constructor-vs-inline-field-initialization – Szab Oct 31 '18 at 18:04
  • Ah, there it is. I couldn't find it when I searched, it definitely is a duplicate question, thanks! – Nicolás Marzano Oct 31 '18 at 18:07

1 Answers1

1

The declaration-site initializations are compiled into all the constructors, in the order they appear. So the only difference between the two approaches is that declaration-site initialization gets "reused", which (as you point out) is convenient but can also be wasteful. Your second example is equivalent to:

public class Foo {
    private String bar;
    private SomeClass bar2;

    public Foo() {
        this.bar = "";
        this.bar2 = new SomeClass();
        // other stuff...
    }

    public Foo(String bar, SomeClass bar2) {
        this.bar = "";
        this.bar2 = new SomeClass();
        this.bar = bar;
        this.bar2 = bar2;
        // other stuff...
    }
}

(By the way: please put a space before your {, unless you're at a company with a coding standard that says not to.)

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81