Skip to content

Flexible Constructor Bodies in Java 25: Executing Code Before super()

Colored sticky notes on a blackboard, connected by chalk arrows

In this article, you will learn:

  • how to execute code in constructors before calling super(...) or this(...) as of Java 25 (available as a preview feature since Java 22),
  • what restrictions exist,
  • what the prologue and epilogue of a constructor are,
  • whether the new features also apply to records and enums,
  • and what to do if the compiler rejects the feature with an error.

Let’s take a step back: Why would you want to execute code before super(...) or this(...)?

Code in Constructors – Status Quo Before Java 25

The following examples show workarounds that were previously required to validate or compute parameters before calling super() or this() – and also what could go wrong if the constructor of the parent class calls a method that is overridden in the child class.

Use Case 1: Parameter Validation

An everyday use case is the validation of parameters of a child class. In the following example, the constructor of Rectangle first calls the constructor of the parent class, Shape, and then validates and sets the width and height:

public class Shape {
  private final Color color;

  public Shape(Color color) {
    this.color = color;
  }
}

public class Rectangle extends Shape {
  private final double width;
  private final double height;

  public Rectangle(Color color, double width, double height) {
    super(color);
    if (width < 0 || height < 0) throw new IllegalArgumentException();
    this.width = width;
    this.height = height;
  }
}

However, validating the parameters before the super constructor is called would be much more efficient. Yet, this is currently only possible with the following extremely unappealing workaround:

public Rectangle(Color color, double width, double height) {
  super(validateParams(color, width, height));
  this.width = width;
  this.height = height;
}

private static Color validateParams(Color color, double width, double height) {
  if (width < 0 || height < 0) throw new IllegalArgumentException();
  return color;
}

Use Case 2: Calculation of an Argument That Is Passed to Several Parameters

Another use case is the calculation of values that are to be passed on to more than one superclass constructor parameter. In the following example, we want to create a square with a given area (we will ignore the fact that a static factory method with a meaningful name would be more suitable than a constructor):

public class Square extends Rectangle {
  public Square(Color color, int area) {
    super(color, Math.sqrt(area), Math.sqrt(area));
  }
}

To avoid calculating the square root of the area twice, we would have to introduce an auxiliary constructor:

public class Square extends Rectangle {
  public Square(Color color, int area) {
    this(color, Math.sqrt(area));
  }

  private Square(Color color, double sideLength) {
    super(color, sideLength, sideLength);
  }
}

However, this is only possible here because area is of the type int. If area were like sideLength of type double, this would not work, as we would then have two constructors with identical signatures.

And if we wanted to make sure that area is not negative beforehand, we would have to introduce a third method, as we are not allowed to execute any other code before this(...):

public class Square extends Rectangle {
  public Square(Color color, int area) {
    this(color, Math.sqrt(validateArea(area)));
  }

  private static double validateArea(int area) {
    if (area < 0) throw new IllegalArgumentException();
    return area;
  }

  private Square(Color color, double sideLength) {
    super(color, sideLength, sideLength);
  }
}

It is hard to see what this code does.

Use Case 3: Calling an Overridden Method in the Super Constructor

We stay with the Shape/Rectangle example and add a printMe() method, which is called in the constructor of Shape and overridden in Rectangle:

public class Shape {
  private final Color color;

  public Shape(Color color) {
    this.color = color;
    printMe();
  }

  void printMe() {
    System.out.println("color = " + color);
  }
}

public class Rectangle extends Shape {
  private final double width;
  private final double height;

  public Rectangle(Color color, double width, double height) {
    super(color);
    if (width < 0 || height < 0) throw new IllegalArgumentException();
    this.width = width;
    this.height = height;
  }

  @Override
  void printMe() {
    super.printMe();
    System.out.println("width = " + width + ", height = " + height);
  }
}

If we now call new Rectangle(Color.RED, 29.7, 21.0), the output is not color = RED and width = 29.7, height = 21.0, but:

color = RED
width = 0.0, height = 0.0

The reason for this is that printMe() is called by the Shape constructor before width and height have been initialized in the Rectangle constructor. printMe() therefore still sees the default values of width and height, i.e., 0.0.

Java Code Before super(...) and this(...)

Java 22 introduced – initially as a preview feature and under the name “Statements before super(…)” – the possibility of executing code before calling super(...) or this(...).

That means that we can now validate the area before calling this(...):

public class Square extends Rectangle {
  public Square(Color color, int area) {
    if (area < 0) throw new IllegalArgumentException(); // ⟵ Validation before `this`
    this(color, Math.sqrt(area));
  }

  private Square(Color color, double sideLength) {
    super(color, sideLength, sideLength);
  }
}

And we no longer need the auxiliary constructor either. We can now accommodate the parameter validation and the calculation of the side length directly in the constructor:

public Square(Color color, int area) {
  if (area < 0) throw new IllegalArgumentException(); // ⟵ Validation before `super`
  double sideLength = Math.sqrt(area);                // ⟵ Calculation before `super`
  super(color, sideLength, sideLength);
}

With this constructor, you can see at a glance what the code does.

Java 23 introduced the possibility of initializing fields before calling super(...). This allows us to write the Rectangle class in the following way:

public class Rectangle extends Shape {
  private final double width;
  private final double height;

  public Rectangle(Color color, double width, double height) {
    this.width = width;    // ⟵ Field initialization before `super`
    this.height = height;  // ⟵ Field initialization before `super`
    super(color);
  }

  . . .
}

When calling new Rectangle(Color.RED, 29.7, 21.0), the printMe() method invoked by the constructor now prints the expected result:

color = RED
width = 29.7, height = 21.0

Why does this work now? The prologue – this.width = width; and this.height = height; – runs in full before super(color), and therefore before the Shape constructor. So when that constructor calls printMe(), width and height are already set. That was impossible before: any code inevitably came after super(…) – and therefore too late.

In general: when an object is created, the prologues are processed first, from the subclass up to the superclass; after that, each constructor runs from its super(…) call onward, from the superclass down. So the fields you set in the prologue are already in place by the time the superclass constructor begins its work.

Flexible Constructor Bodies have been available as a finalized feature since Java 25.

Constructor Prologue and Epilogue

The block before super(...) or this(...) is called the “prologue”.

Code after calling super(...) or this(...) or code in a constructor without calling super(...) or this(...) is called the “epilogue”.

Restrictions

In the prologue, the code may initialize fields but must not read any fields of the class and must not call any non-static methods of the class. It must also not create instances of non-static inner classes, as these would then have a reference to the potentially uninitialized parent object.

The prologue of the constructor of an inner class, on the other hand, can access fields and methods of the outer class without restriction.

Records and Enums

While records and enums can’t extend a class of your choosing, their constructors can still invoke alternative constructors via this(…).

Code that complies with the above-mentioned restrictions may now also be executed before that.

Compiler Error: “Flexible Constructor Bodies is only available with source level 25 and above”

Eclipse and the Java extension for Visual Studio Code report this error for the code above when the project’s source level is below 25:

The Java feature 'Flexible Constructor Bodies' is only available with source level 25 and above

The cause is the source level of the project, not the installed JDK – both IDEs use the Eclipse compiler, which phrases the message this way.

javac phrases it differently. With a source level below 25 – because the build tool still sets --release 21, for example – it reports:

Rectangle.java:8: error: flexible constructors is not supported in -source 21
    this.width = width;
    ^
  (use -source 25 or higher to enable flexible constructors)

On Java 22, 23, and 24, where the feature was still a preview, the message reads:

Rectangle.java:8: error: flexible constructors is a preview feature and is disabled by default.
    this.width = width;
    ^
  (use --enable-preview to enable flexible constructors)

In Java 22, the feature is still called “statements before super()” here.

The fix is to raise the source level to 25: in Maven via the maven.compiler.release property, in Gradle via a Java toolchain with language version 25, in IntelliJ via File→Project Structure→Project Settings→Project→Project language level, and in Eclipse via Project→Properties→Java Compiler→Compiler compliance level. Visual Studio Code takes the level from the Maven or Gradle build file.

If your project still runs on Java 22, 23, or 24, you can compile the code with --enable-preview --release <version> – and then have to start the program with --enable-preview as well. Without that flag, the class loader rejects the class:

Exception in thread "main" java.lang.UnsupportedClassVersionError: Preview features are not enabled for Rectangle (class file version 68.65535). Try running with '--enable-preview'

History

Flexible Constructor Bodies were defined in the following JDK Enhancement Proposals:

Conclusion

Executing code before super(...) or this(...) allows fields to be initialized and parameters to be validated or calculated before the super constructor or an alternative constructor is called. That makes the code safer and enables much more expressive code than the workarounds we had to construct in the past.

Flexible Constructor Bodies were finalized in Java 25 and have been available without a preview flag ever since. If you’re still on Java 22, 23, or 24, you can enable the feature there as a preview using --enable-preview --release <version>.

What should I cover next? The best way for me to find out is through your feedback: a review on my ProvenExpert profile shows me which topics matter to you – and motivates me to write more articles.

👉 Leave a review

This subject in your own code?

You have read the article – in the training your team works with it. Over 2 days we go through the subjects on your own projects instead of constructed examples.

Hands-on, easy to understand, and directly applicable to your day-to-day project work. Instead of theory, I teach principles that help you write code that is better, more maintainable, and more performant in the long run.

Java 25 TrainingSee all trainings

Become a Better Java Developer

My free newsletter keeps you ahead. Modern Java: new versions & features, performance, and JVM insights – once a month.

Search