Default Constructor VS. Inline Field Initialization

Java constructor vs inline field initialisation

I'm wondering in both cases will it actually initially assign 5, and then update this with 10

Yes. The constructor will:

  1. Call super().
  2. Execute any inline initializations and anonymous initialization blocks.
  3. Execute the remaining body of the constructor.

This is specified in more detail in the JLS #12.5-6.

The difference assigning a value to a field and initializing the field value in constructor

The two snippets would behave the same way. You could say that initializing the field directly is a form of syntactic sugar. It becomes convenient if you have multiple constructors and don't want to repeat the same initialization in all of them.

Inline field initialization vs builder which is better

Builder pattern need to be considered when faced with many constructor parameters.
Constructors do not scale well with large number of optional parameters.

Refer: Item 2 in Effective Java http://www.informit.com/articles/article.aspx?p=1216151&seqNum=2

If the count of your fields will not increase to a large number then I will prefer to go with Inline field initialization as it means writing less code which is always good.

Initialize class fields in constructor or at declaration?

My rules:

  1. Don't initialize with the default values in declaration (null, false, 0, 0.0…).
  2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
  3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
  4. Be consistent in your practice (the most important rule).

Inline field initialization

Since you have to write down the constructor explicitly, this too has to be done explicitly. You could write a macro to do it automatically though.

type
MyT = object of RootObj
str*: string

proc initMyT(str = "<initial>"): MyT =
result.str = str

Differences in these two ways of initializing instance variables?

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.)



Related Topics



Leave a reply



Submit