Flexible constructor bodies go final
Validation before super() is now supported, deleting a long-standing workaround.
Open this lesson in the learning hubKey points
- JEP 513 finalises statements before
super(...)orthis(...). - Those statements form a prologue and may not read or leak
this. - So argument validation, normalisation and defensive copies can happen before the superclass runs.
- The static-helper trick -
super(check(x))- is no longer needed. - Initialisation safety is preserved: nothing can observe the object before the superclass finishes.
Example
// Java 25 (JEP 513) - final:
//
// Positive(int value) {
// if (value <= 0) throw new IllegalArgumentException("must be positive");
// super(value);
// }
//
// Java 21 forces the check into a static method just to run it first:
public class Main {
static class Amount {
final int value;
Amount(int value) { this.value = value; }
}
static class Positive extends Amount {
Positive(int value) { super(check(value)); }
private static int check(int v) {
if (v <= 0) throw new IllegalArgumentException("must be positive, got " + v);
return v;
}
}
public static void main(String[] args) {
System.out.println("accepted: " + new Positive(7).value);
try { new Positive(0); }
catch (IllegalArgumentException e) { System.out.println("rejected: " + e.getMessage()); }
}
}
You can now validate before super() without a static helper, and the safety rule is unchanged.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 25 Course course, and every lesson in it is listed on the Java 25 Course contents page.