Java 25 (LTS) · Topic 2 of 4
Flexible constructor bodies
Definition​
Flexible constructor bodies (Java 25) let you run statements before calling super(...) or this(...), as long as they do not use the object being built. You can validate or compute arguments first instead of using awkward static helper methods.
Example code​
Validating an argument before calling super
class Account {
final long balance;
Account(long balance) { this.balance = balance; }
}
class Savings extends Account {
Savings(long deposit) {
if (deposit < 0) throw new IllegalArgumentException("deposit must not be negative"); // before super
long bonus = deposit / 10;
super(deposit + bonus);
}
}
class Demo {
public static void main(String[] args) {
System.out.println(new Savings(1_000).balance);
try {
new Savings(-5);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
// Output:
// 1100
// deposit must not be negative
Finished this page? Track your progress (saved only in your browser).