107. Flexible Constructor Bodies: Statements Before super()
Flexible constructor bodies allow statements to precede super(...) or this(...), permitting argument validation, preprocessing, and defensive copies before invoking superclass constructors.
Explanation
Since Java 1.0, the language strictly enforced that if a constructor called super(...) or this(...), that call had to be the very first statement in the constructor body. This ancient rule prevented access to uninitialized this fields, but it also forced awkward workarounds when constructor arguments needed validation, calculation, or preparation before passing them up the hierarchy.
Developers were forced into convoluted static helper methods: ``java // Legacy workaround: public SubClass(int val) { super(validateAndTransform(val)); } ``
JEP 482 (Java 23 / 24) introduces Flexible Constructor Bodies. Constructors can now contain arbitrary statements in the prologue before the explicit constructor invocation (super(...) or this(...)). The only restriction is that prologue code cannot refer to the instance being created (this) or its instance fields. It can safely validate arguments, throw IllegalArgumentException, or prepare complex dependencies before the parent constructor runs.
Example
// Legacy workaround:
public SubClass(int val) {
super(validateAndTransform(val));
}Sources
- https://openjdk.org/jeps/482 โ JEP 482: Flexible Constructor Bodies (Second Preview)
- https://openjdk.org/jeps/447 โ JEP 447: Statements before super(...) (Java 22)