Constructioneasy0-2 years

`new Config("api")` prints `name=null` from inside the constructor, even though `this.name = name` is the very first line of the constructor body someone wrote. The field being read is a *different* field, assigned by an initialiser. What's actually happening, and why does the order matter?

A field initialiser (private final int retries = compute();) doesn't run at some vague "before the constructor" time — javac copies it into the start of every constructor that doesn't delegate with this(...), running before the constructor body the developer actually wrote. So if compute() reads another field (name) that's assigned later in the constructor's own body, compute() runs while that field is still at its zeroed default (null for a reference), not the value the caller passed in. The fix is to move the computation into the constructor body, after the field it depends on has actually been assigned, or make the computation not depend on that field at all.

The lesson behind it →
More on Construction