Flexible constructor bodies
Validate arguments before calling super(), without static helper tricks.
static class Person {
final String name;
Person(String name) {
this.name = name;
}
}
static class Employee extends Person {
final int level;
Employee(String name, int level) {
if (level < 1) {
throw new IllegalArgumentException("level must be at least 1, got " + level);
}
super(name);
this.level = level;
}
}
void main() {
var dana = new Employee("Dana", 2);
IO.println(dana.name + " is level " + dana.level);
try {
new Employee("Eli", 0);
} catch (IllegalArgumentException e) {
IO.println("Rejected before super(): " + e.getMessage());
}
} Run with JDK 25: java FlexibleConstructor.java
Before Java 25, super(...) had to be the first statement in a constructor. To validate an argument first, you needed a static helper method inside the super(...) call.
Java 25 lets you run statements before super(...) or this(...), as long as they do not use the object under construction.
Output
Dana is level 2
Rejected before super(): level must be at least 1, got 0
Rules of thumb
- Good before
super(...): validating, normalizing or computing arguments. - Not allowed before
super(...): reading or calling anything onthis.