Flexible constructor bodies

suggest change

Until Java 25 an explicit constructor call, super(...) or this(...), had to be the very first statement of a constructor. Since Java 25 (JEP 513, final) you can put statements before it. This is called a flexible constructor body.

class PositiveBig extends java.math.BigInteger {
    PositiveBig(long value) {
        if (value <= 0) {
            throw new IllegalArgumentException("not positive: " + value);
        }
        super(Long.toString(value));
    }
}

The feature was a preview in Java 22, 23 and 24 (JEPs 447, 482 and 492, the first one called "statements before super(...)"). In Java 25 it's a standard feature: no --enable-preview is needed, but you do need --release 25 or newer:

$ javac --release 21 New.java
New.java:17: error: flexible constructors is not supported in -source 21
        super(Long.toString(value));
             ^
  (use -source 25 or higher to enable flexible constructors)
1 error

The code before the constructor call is the prologue, and the code after it is the epilogue:

Child(String arg) {
    // prologue: runs before the superclass constructor;
    // the object isn't initialized yet, so `this` is off limits
    super(arg);
    // epilogue: runs after the superclass constructor; same rules as always
}

If a constructor has no explicit super(...) or this(...), the compiler still inserts super() at the start, and the whole body is an epilogue. For the basics of constructors and constructor chaining see Constructors, Call parent constructor and super keyword.

Validating arguments before calling super

Validating arguments is the most common reason to want code before super(...). Before Java 25 it had to be squeezed into the argument list, usually through a static helper method:

class PositiveBig extends java.math.BigInteger {
    PositiveBig(long value) {
        super(verify(value));   // validation must hide in a static helper
    }

    private static String verify(long value) {
        if (value <= 0) {
            throw new IllegalArgumentException("not positive: " + value);
        }
        return Long.toString(value);
    }
}

With a flexible constructor body the check is written where it belongs, at the top of the constructor, and the superclass constructor isn't run at all when the argument is bad (it fails fast instead of doing work that's thrown away):

public class New {
    public static void main(String[] args) {
        System.out.println(new PositiveBig(42).longValue());
        try {
            new PositiveBig(-5);
        } catch (IllegalArgumentException e) {
            System.out.println("error: " + e.getMessage());
        }
    }
}

class PositiveBig extends java.math.BigInteger {
    PositiveBig(long value) {
        if (value <= 0) {
            throw new IllegalArgumentException("not positive: " + value);
        }
        super(Long.toString(value));
    }
}
42
error: not positive: -5

Computing arguments for super or this

The prologue can contain any ordinary code: local variables, if, loops, switch, try/catch, calls to static methods. That makes it easy to compute several superclass arguments from one input.

Here ParsedRange turns "10..20" into two ints for the Range constructor:

public class Ranges {
    public static void main(String[] args) {
        System.out.println(new Range(3, 7));
        System.out.println(new ParsedRange(" 10..20 "));
        System.out.println(new ParsedRange("5"));
        try {
            new ParsedRange("9..1");
        } catch (IllegalArgumentException e) {
            System.out.println("error: " + e.getMessage());
        }
    }
}

class Range {
    final int lo, hi;

    Range(int lo, int hi) {
        if (lo > hi) throw new IllegalArgumentException(lo + " > " + hi);
        this.lo = lo;
        this.hi = hi;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "[" + lo + ", " + hi + "]";
    }
}

class ParsedRange extends Range {
    ParsedRange(String text) {
        String s = text.strip();
        int dots = s.indexOf("..");
        int lo, hi;
        if (dots < 0) {
            lo = hi = Integer.parseInt(s);
        } else {
            lo = Integer.parseInt(s.substring(0, dots));
            hi = Integer.parseInt(s.substring(dots + 2));
        }
        super(lo, hi);
    }
}
Range[3, 7]
ParsedRange[10, 20]
ParsedRange[5, 5]
error: 9 > 1

Without the prologue, sharing one computation between two arguments needed a trick: a static method returning an array (or a small holder object) and an extra private constructor to unpack it:

class ParsedRange extends Range {
    ParsedRange(String text) {
        this(parse(text));               // compute once...
    }

    private ParsedRange(int[] bounds) {  // ...then unpack in a private constructor
        super(bounds[0], bounds[1]);
    }

    private static int[] parse(String text) {
        String[] parts = text.strip().split(java.util.regex.Pattern.quote(".."));
        int lo = Integer.parseInt(parts[0]);
        int hi = parts.length > 1 ? Integer.parseInt(parts[1]) : lo;
        return new int[] { lo, hi };
    }
}

The same applies to this(...): a constructor that delegates to another constructor of the same class can prepare the arguments first (see the record and enum examples below).

Initializing fields before super

The prologue may assign fields of the class being constructed. This fixes an old Java trap: a superclass constructor that calls an overridable method.

Constructors run from the top of the hierarchy down. When Shape() runs, the Square part of the object hasn't been initialized yet, so the overridden describe() sees default values:

public class Shapes {
    public static void main(String[] args) {
        new Square(5);
    }
}

abstract class Shape {
    Shape() {
        System.out.println("created " + describe());
    }

    abstract String describe();
}

class Square extends Shape {
    private final int side;
    private String color = "red";

    Square(int side) {
        super();
        this.side = side;
    }

    @Override
    String describe() {
        return "square side=" + side + " color=" + color;
    }
}
created square side=0 color=null

side is 0 even though it's final, and color is null even though it has an initializer. Field initializers and instance initializer blocks run right after super(...) returns, so they are too late as well.

If the fields are assigned in the prologue, they are already set when the superclass constructor calls back into the subclass:

public class Shapes2 {
    public static void main(String[] args) {
        new Square(5);
        new Circle(2.5);
    }
}

abstract class Shape {
    Shape() {
        System.out.println("created " + describe());
    }

    abstract String describe();
}

class Square extends Shape {
    private final int side;
    private final String color;

    Square(int side) {
        this.side = side;
        this.color = "red";
        super();
    }

    @Override
    String describe() {
        return "square side=" + side + " color=" + color;
    }
}

class Circle extends Shape {
    private final double radius;
    private final java.util.List<String> tags;

    Circle(double radius) {
        if (radius <= 0) throw new IllegalArgumentException("radius");
        this.radius = radius;
        this.tags = java.util.List.of("round", radius > 2 ? "big" : "small");
        super();
    }

    @Override
    String describe() {
        return "circle r=" + radius + " tags=" + tags;
    }
}
created square side=5 color=red
created circle r=2.5 tags=[round, big]

Note that color no longer has an initializer: a field with an initializer can't be assigned in the prologue (see the next section). Move the value into the constructor instead.

This is a big deal for frameworks and class hierarchies where the base class calls template methods (init(), createLayout(), describe()) from its constructor. Calling overridable methods from a constructor is still best avoided, but when you can't change the superclass, early field assignment makes the subclass safe.

The JVM always allowed this: javac has been storing fields before super() for years, for example the hidden reference to the enclosing instance in inner classes. The bytecode of the new Square constructor shows the two putfield instructions before the call to Shape.<init>:

$ javap -c -p Square
  Square(int);
    Code:
         0: aload_0
         1: iload_1
         2: putfield      #1                  // Field side:I
         5: aload_0
         6: ldc           #7                  // String red
         8: putfield      #9                  // Field color:Ljava/lang/String;
        11: aload_0
        12: invokespecial #13                 // Method Shape."<init>":()V
        15: return

What the prologue may not do

Before super(...) returns, the object is in an early construction context. The rule is simple: you may not use the object being constructed, except to assign its fields. In practice that means:

Here's what javac reports for each:

class Base {
    int baseField;
    Base(int x) {}
    void hello() {}
}

class Bad extends Base {
    int a;
    int b = 10;
    final int c;

    Bad(int x) {
        hello();              // 1: instance method call
        this.hello();         // 2: explicit this
        int y = a;            // 3: read own field
        b = x;                // 4: assign field that has an initializer
        a = x;                // OK: assign field with no initializer
        System.out.println(this); // 5: use this as a value
        int z = super.baseField;  // 6: superclass field
        Runnable r = () -> System.out.println(c); // 7: lambda capturing this
        super(x);
    }
}
$ javac Bad.java
Bad.java:13: error: cannot reference hello() before supertype constructor has been called
        hello();              // 1: instance method call
        ^
Bad.java:14: error: cannot reference this before supertype constructor has been called
        this.hello();         // 2: explicit this
        ^
Bad.java:15: error: cannot reference a before supertype constructor has been called
        int y = a;            // 3: read own field
                ^
Bad.java:16: error: cannot assign initialized field 'b' before supertype constructor has been called
        b = x;                // 4: assign field that has an initializer
        ^
Bad.java:18: error: cannot reference this before supertype constructor has been called
        System.out.println(this); // 5: use this as a value
                           ^
Bad.java:19: error: cannot reference super before supertype constructor has been called
        int z = super.baseField;  // 6: superclass field
                ^
Bad.java:20: error: cannot reference c before supertype constructor has been called
        Runnable r = () -> System.out.println(c); // 7: lambda capturing this
                                              ^
7 errors

There are also structural rules. The super(...) or this(...) call is still required to be a top-level statement of the constructor body, exactly once, so it can't be inside an if, a loop or a try block. And the prologue can't return (it may throw, though):

class Bad2 extends Base {
    int a;

    class Inner {}

    Bad2(int x) {
        a = x;
        int copy = a;            // 1: read after assigning
        if (x < 0) return;       // 2: return in prologue
        new Inner();             // 3: inner class needs this
        super(x);
    }

    Bad2(String s) {
        if (s.isEmpty()) {
            super(0);            // 4: not a top-level statement
        } else {
            super(s.length());
        }
    }

    Bad2(long n) {
        try {
            super((int) n);      // 5: inside try
        } catch (RuntimeException e) {}
    }
}
$ javac Bad2.java
Bad2.java:12: error: cannot reference a before supertype constructor has been called
        int copy = a;            // 1: read after assigning
                   ^
Bad2.java:14: error: cannot reference this before supertype constructor has been called
        new Inner();             // 3: inner class needs this
        ^
Bad2.java:13: error: 'return' not allowed before explicit constructor invocation
        if (x < 0) return;       // 2: return in prologue
                   ^
Bad2.java:20: error: explicit constructor invocation not allowed here
            super(0);            // 4: not a top-level statement
                 ^
Bad2.java:22: error: explicit constructor invocation not allowed here
            super(s.length());
                 ^
Bad2.java:28: error: explicit constructor invocation not allowed here
            super((int) n);      // 5: inside try
                 ^
6 errors

To choose between different superclass arguments, compute them into local variables in the prologue (as in ParsedRange above) and make a single super(...) call. If you need a value both before and after super(...), keep it in a local variable: locals declared in the prologue are visible in the epilogue too.

What the prologue may do

Everything that doesn't touch the new object is allowed. That includes local classes and records, lambdas that don't capture this, static methods, and, for an inner class, the fields and methods of the enclosing instance, which was fully constructed long ago:

import java.util.*;
import java.util.function.*;

public class Allowed {
    String prefix = "outer-";

    class Child extends Base {
        final String name;

        Child(String raw) {
            // the enclosing instance (Allowed.this) is fully constructed
            String full = prefix + raw;

            // local variables, loops, static methods, local records, lambdas
            record Stats(int letters, int digits) {}
            int letters = 0, digits = 0;
            for (char ch : full.toCharArray()) {
                if (Character.isLetter(ch)) letters++;
                else if (Character.isDigit(ch)) digits++;
            }
            var stats = new Stats(letters, digits);
            Function<String, String> upper = String::toUpperCase;

            name = upper.apply(full);     // assign a field of this class
            super(stats.toString());
        }
    }

    public static void main(String[] args) {
        Allowed outer = new Allowed();
        Child c = outer.new Child("abc42");
        System.out.println(c.name + " / " + c.info);
    }
}

class Base {
    final String info;
    Base(String info) { this.info = info; }
}
OUTER-ABC42 / Stats[letters=8, digits=2]

Records and enums

Records and enums can't call super(...) (their superclass is fixed: java.lang.Record or java.lang.Enum), but they use this(...), and its prologue works the same way.

A non-canonical record constructor must delegate to another constructor with this(...). Before Java 25 that meant all parsing and validation had to fit into the argument expressions. Now it can be written as normal statements. The canonical constructor (including the compact form) can't contain super(...) or this(...) at all, so nothing changes there:

import java.time.LocalTime;

public class Records {
    record TimeRange(LocalTime start, LocalTime end) {
        TimeRange {   // compact canonical constructor: no super(...)/this(...) allowed
            if (end.isBefore(start)) {
                throw new IllegalArgumentException(start + " is after " + end);
            }
        }

        // non-canonical constructors must delegate with this(...)
        TimeRange(String text) {
            String[] parts = text.split("-");
            if (parts.length != 2) {
                throw new IllegalArgumentException("expected HH:MM-HH:MM, got " + text);
            }
            this(LocalTime.parse(parts[0].strip()), LocalTime.parse(parts[1].strip()));
        }
    }

    enum Planet {
        MERCURY(3.303e+23, 2.4397e6),
        EARTH("5.976e+24 / 6.37814e6");

        final double mass, radius;

        Planet(double mass, double radius) {
            this.mass = mass;
            this.radius = radius;
        }

        Planet(String spec) {
            String[] p = spec.split("/");
            this(Double.parseDouble(p[0].strip()), Double.parseDouble(p[1].strip()));
        }
    }

    public static void main(String[] args) {
        System.out.println(new TimeRange("09:00 - 17:30"));
        try {
            new TimeRange("9:00");
        } catch (IllegalArgumentException e) {
            System.out.println("error: " + e.getMessage());
        }
        for (Planet p : Planet.values()) {
            System.out.printf("%s mass=%.3e radius=%.0f%n", p, p.mass, p.radius);
        }
    }
}
TimeRange[start=09:00, end=17:30]
error: expected HH:MM-HH:MM, got 9:00
MERCURY mass=3.303e+23 radius=2439700
EARTH mass=5.976e+24 radius=6378140

More on these in Records and Enums with constructors.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents