When would you put statements before `super(...)` in a Java constructor, what can they not touch, and how does that compare with a static helper?
answer
- prologue before, epilogue after
- validate, compute, or protect a field
- no use of this, even implicitly
- simple assignment to uninitialized own fields
- helper needs an argument, cannot assign
basics
~20 sSince Java 25, use statements before super(...) to validate or compute arguments, or to assign a field an overridden method reads. They cannot use the instance except that assignment. A static helper validates too, but cannot set fields.
solid answer
~50 sSince Java 25 a constructor may run a **prologue** before `super(...)` or `this(...)`. I use it to fail fast on bad arguments, to compute a value shared by several arguments, and to assign a field that an overridden method reads when the superclass constructor calls it, so the override sees the real value and not the default. The prologue cannot use the instance: no reading fields, even one it just assigned, no instance methods, no `super.x`, no `new Inner()`. The one exception is a simple assignment to a field of this class that has no initializer. The older `super(verifyAge(age))` still works and fails fast too, and it is reusable, but it needs an argument to hang on, gets clumsy for shared values and cannot assign fields. The invocation itself still cannot sit inside an `if` or `try`.
code
java · 21 linesclass Person {
Person(int age) {
show(); // dispatches to Employee.show()
}
void show() { }
}
class Employee extends Person {
private final String officeId;
Employee(int age, String officeId) {
if (age < 18 || age > 67) // fail fast: Person's constructor never runs
throw new IllegalArgumentException("age " + age);
this.officeId = officeId; // no initializer, simple assignment: allowed
super(age);
}
@Override void show() {
System.out.println("office=" + officeId);
}
}go deeper
Recall that since Java 25 statements may come before super or this, that they are called the prologue, and that they cannot use the object being built.
Explain the early construction context and its one exception, a simple assignment to a field with no initializer. Show how assigning first changes what an overridden method sees, and what a static helper can and cannot do.
Show you can place it in real hierarchies: fail fast on expensive superclasses, protect a field against an override you cannot remove, and spot initializer blocks that overwrite the value afterwards.
The call is about style and migration: when to rewrite working helpers, which source level a library may target, and whether analyzers and style checks in the build already accept the new shape.
## What changed in Java 25 Until Java 25, the first statement of a constructor had to be an **explicit constructor invocation**, `super(...)` or `this(...)`, or the compiler inserted `super()`. **Flexible constructor bodies** (JEP 513, previewed in JDK 22, 23 and 24) let statements come first. The statements before the invocation form the **prologue**; those after it form the **epilogue**. A constructor with no explicit invocation has an empty prologue and starts with an implicit `super()`, so existing code keeps its meaning. The prologue runs before the superclass constructor. Prologues therefore run from the bottom of the hierarchy up, and epilogues from the top down. Field initializers and initializer blocks keep their place, right after `super(...)` returns; the construction-order questions cover that sequence in full. ## When to use it - **Fail fast.** Reject bad arguments before the superclass does any work: `if (age < 18) throw new IllegalArgumentException(...); super(age);`. - **Compute or share a value.** A local variable can feed several arguments, and a `try` statement can surround the computation: `int v; try { v = Integer.parseInt(s); } catch (RuntimeException e) { v = 0; } super(v, v);`. - **Protect a field.** If a superclass constructor calls a method this class overrides, that override runs before the epilogue. Assigning the field in the prologue means it sees the real value, not `null` or `0`. This works on a blank `final` field too, which is a `final` field declared with no initializer. Prologues also work before `this(...)`, which is how non-canonical record constructors and enum constructors benefit. ## What the prologue cannot touch The prologue and the invocation's argument list are together an **early construction context**: code there must not use the object being built. The compiler enforces this: | In the prologue | Result | |---|---| | Parameters, locals, static members, local classes | allowed | | `throw`, `if`, loops, `try` as ordinary statements | allowed | | `x = v` or `this.x = v`, field of this class, no initializer | allowed | | An enclosing instance from an inner class, `Outer.this.y` | allowed | | Reading that same field: `x`, `this.x`, `x += 1`, `x++` | error | | `x = v` where `x` has an initializer | error | | Inherited fields, `super.x`, `super.m()` | error | | Instance methods, including `toString()`; passing `this` | error | | `new Inner()` of its own inner class, which means `this.new Inner()` | error | | Assigning a field inside a lambda or inner class body | error | | `return` | error | javac 27 words the read error as `reference to x may only appear after an explicit constructor invocation`; javac 25 says `cannot reference x before supertype constructor has been called`. The invocation has limits of its own. A constructor body holds at most one, and it must be a direct statement of the body, so `if (flag) super(1); else super(2);` and `try { super(); } catch ...` do not compile. The JVM would allow the `if` form, with one invocation per code path, but the language grammar does not. The `try` form fails at both levels: JEP 513 records that the JVM also bars an invocation from a `try` block. ## Compared with the static helper The old workaround hides the logic in an argument: `super(verifyAge(age))`, with `verifyAge` a `private static` method that throws or returns its input. It is still legal. | Need | Static helper in an argument | Prologue | |---|---|---| | Run before the superclass constructor | yes | yes | | Check with no matching argument, such as before `super()` | no argument to run in | plain `if` | | Check across several parameters | helper takes them all, returns one | plain `if` | | Share a computed value across arguments | call it twice, or add a private constructor | a local variable | | Assign this class's field first | not possible | yes | | Reuse across constructors | one named method | repeat it, or call a helper from it | | Source level | any | 25 or later | At `--release 24` or lower, javac rejects a prologue with an error such as `flexible constructors is not supported in -source 24`. An instance helper never worked and still does not, since `super(check())` uses `this`. The two combine well: a prologue can call a static helper, so reuse and clarity need not compete. ## Traps - **Initializer blocks still run later.** With `String tag; { tag = "block"; }`, a prologue's `tag = "prologue"` is what an override sees during `super(...)`, and afterwards the block overwrites it. - **A blank `final` before `this(...)`.** The alternate constructor counts as assigning it, so javac reports `variable x might already have been assigned`. A non-`final` field is allowed: the target constructor sees the value and may replace it. - **A field with an initializer cannot be protected** until you move the initial value into the prologue. - **It protects only this class.** Another subclass that does not assign in its prologue still exposes defaults, so an overridable call from a constructor stays a design smell. - **Tools lag.** JEP 513 warns that analyzers and style checkers have the first-statement rule built in.
- Why can a prologue not read a field it assigned on the previous line?The exception covers one thing: a simple assignment to a field of this class with no initializer. A read still goes through `this`, implicitly or explicitly, and that is a use of the object under construction, so `x = 1; int y = x;` fails. Keep the value in a local, assign the field from it, and read the local.
- Does a value assigned in the prologue always survive to the end of the constructor?No. Instance initializer blocks run right after `super(...)` returns, so a block that assigns the same field overwrites it, and the epilogue can reassign a non-`final` field too. A `final` field assigned in the prologue is protected: javac rejects a second assignment with `variable x might already have been assigned`.
- What does a prologue before `this(...)` allow that differs from one before `super(...)`?The same early construction rules apply, with one difference on blank `final` fields. Assigning one before `this(...)` is an error, because the alternate constructor counts as assigning it. A non-`final` field may be assigned there, the target sees the value and may replace it. Non-canonical record constructors gain prologues this way.
- Since Java 25 a constructor can run any code before super, including instance methods.
- A field assigned in the prologue can be read on the next line.
- A prologue can assign any field of the class, even one declared with an initializer.
- super(...) may now sit inside an if or try block, as long as it runs once.
- A static helper cannot fail fast, because the superclass constructor starts before arguments are evaluated.
- Assigning in the prologue makes overridable calls from constructors safe for every subclass.
- Flexible constructor bodies
- Java 25pre-release 22
Assumes Java 27; flexible constructor bodies are final since Java 25, previewed in 22 to 24, and every compile outcome here matches at 25 except javac's error wording.
context
- JEP 513: Flexible Constructor Bodiesopenjdk.org
- Chapter 8. Classesdocs.oracle.com
- Chapter 12. Executiondocs.oracle.com