00:00

Flexible Constructor Bodies in Java 25

Last updated: · Standard (Java 25)

Before Java 25, the call to super(...) or this(...) had to be the first statement in a constructor. Java 25 (JEP 513) relaxes that rule: a constructor can run statements first, in a part called the prologue, as long as they do not use the object being built.

This tutorial shows the two most useful patterns, validating arguments and initialising fields early, and the restrictions the compiler enforces.

1. Why Were Flexible Constructor Bodies Added?

Developers often needed to check or prepare arguments before calling the superclass constructor. The workaround was a static helper method called inside the super(...) argument list, which is awkward. A more serious problem: if a superclass constructor calls an overridden method, the subclass method runs before the subclass fields are assigned, so it sees default values such as null.

2. Syntax and Rules

Syntax.java
Employee(String name, int salary) {
    if (salary <= 0) throw new IllegalArgumentException();   // prologue
    String clean = name.strip();                            // prologue
    this.salary = salary;                                   // allowed: assign own field
    super(clean);                                           // explicit constructor call
    log("created " + this.name);                            // epilogue: normal code
}
  • The prologue may declare local variables, compute values, throw exceptions and assign fields of the class being constructed.
  • It may not read fields, call instance methods or pass this anywhere, because the object is not fully initialised.
  • Code after super(...) (the epilogue) behaves exactly as before.

3. Practical Examples

Example 1: Validate before the superclass runs

ValidateFirst.java
public class ValidateFirst {
    static class Person {
        final String name;
        Person(String name) {
            System.out.println("  Person constructor runs");
            this.name = name;
        }
    }

    static class Employee extends Person {
        final int salary;

        Employee(String name, int salary) {
            // Prologue (Java 25): statements before super(...)
            if (salary <= 0) {
                throw new IllegalArgumentException("salary must be positive");
            }
            String clean = name.strip();            // compute an argument first
            this.salary = salary;                   // fields of this class may be assigned
            super(clean);                           // explicit constructor call
            System.out.println("  Employee ready: " + this.name + ", " + this.salary);
        }
    }

    public static void main(String[] args) {
        new Employee("  Asha ", 90_000);
        try {
            new Employee("Ravi", -1);
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected before Person() ran: " + e.getMessage());
        }
    }
}
Output
  Person constructor runs
  Employee ready: Asha, 90000
Rejected before Person() ran: salary must be positive

The invalid salary is rejected before Person() prints anything, so no half-built object is created.

Example 2: Fixing the overridden-method trap

Widget's constructor calls the overridable render(). Assigning label before super() means the override sees the real value.

OverrideTrap.java
public class OverrideTrap {
    static abstract class Widget {
        Widget() {
            render();                               // calls an overridable method
        }
        abstract void render();
    }

    static class OldButton extends Widget {
        private final String label;
        OldButton(String label) {
            super();                                // super runs first (old style)
            this.label = label;
        }
        void render() { System.out.println("OldButton label = " + label); }
    }

    static class NewButton extends Widget {
        private final String label;
        NewButton(String label) {
            this.label = label;                     // assigned BEFORE super() in Java 25
            super();
        }
        void render() { System.out.println("NewButton label = " + label); }
    }

    public static void main(String[] args) {
        new OldButton("Save");                      // sees the default value null
        new NewButton("Save");                      // sees the real value
    }
}
Output
OldButton label = null
NewButton label = Save

Example 3: What the prologue cannot do

ThisInPrologue.java
public class ThisInPrologue {
    static class Base { Base(int x) { } }

    static class Derived extends Base {
        int size = 3;
        Derived() {
            int doubled = size * 2;   // reading a field of "this" before super() is not allowed
            super(doubled);
        }
    }

    public static void main(String[] args) {
        new Derived();
    }
}
Compiler output
ThisInPrologue.java:7: error: cannot reference size before supertype constructor has been called
            int doubled = size * 2;   // reading a field of "this" before super() is not allowed
                          ^
1 error

4. Prologue and Epilogue

Constructor phases in Java 25 The prologue runs first and may validate arguments and assign fields, then the superclass constructor runs, then the epilogue runs with full access to this. prologue validate, compute, assign fields super(...) superclass constructor epilogue normal constructor code
Figure 1: The object becomes usable only after super(...) returns, so the prologue cannot read it.

5. Important Points and Best Practices

  • Use the prologue for argument checks and for fields that overridden methods may read.
  • Keep it short; complex logic still belongs in static helper methods or factories.
  • Records benefit too: a non-canonical record constructor can now prepare values before calling this(...).
  • Avoid calling overridable methods from constructors at all when you can; the prologue is a fix, not an invitation.

6. Summary

  • Java 25 (JEP 513) allows statements before super(...) and this(...).
  • The prologue can validate arguments and assign the class's own fields.
  • It cannot read fields or call instance methods.
  • Early field assignment fixes the overridden-method-in-constructor trap.

Related Tutorials

7. References