Why does calling a record accessor inside a compact constructor return default field values?

19 hours ago 1
ARTICLE AD BOX

This is normal Java behaviour, and it works the same for "normal classes". For example, the following also compiles fine.

public class DummyClass { private final int x; DummyClass(int x) { x = getX(); this.x = x; } public int getX() { return x; } }

From a compiler perspective, the checking done is "incomplete". For the method call (this.x() in your question, getX() in my example), the compiler only checks that the method return type is assignment compatible with int (the type of parameter x). It does not check if at that point the method references a variable that is not yet definitely assigned. So from the compiler's perspective, everything is fine.

And at runtime, x does actually have a value at that point, even though it hasn't been assigned yet in the constructor, it is 0, so it also doesn't result in a runtime error or other undefined behaviour (like in some other languages).

Mark Rotteveel's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article