Flexible constructor bodies (2nd preview)

Java 23 Course · lesson 11 of 15 · 4 min read

Validate arguments before calling super(), instead of after it is too late.

Open this lesson in the learning hub

Key points

  • Java always required super(...) or this(...) to be the very first statement.
  • So you could not validate an argument before the superclass constructor ran with it.
  • The workaround was a static helper method purely to sneak a check in - a well-known ugly idiom.
  • JEP 482 allows statements before super(...), as long as they do not touch this.
  • The safety property is preserved: the object still cannot be observed before the superclass initialises it.

Example

// Java 23 preview (JEP 482) would allow:
//
//   Positive(int value) {
//       if (value <= 0) throw new IllegalArgumentException("must be positive");
//       super(value);                 // validation BEFORE super
//   }
//
// The Java 21 workaround - a static method that exists only to hold the check:
public class Main {
    static class Number {
        final int value;
        Number(int value) { this.value = value; }
    }

    static class Positive extends Number {
        Positive(int value) {
            super(check(value));       // the only way to validate first
        }
        private static int check(int v) {
            if (v <= 0) throw new IllegalArgumentException("must be positive, got " + v);
            return v;
        }
    }

    public static void main(String[] args) {
        System.out.println("valid   : " + new Positive(5).value);
        try {
            new Positive(-1);
        } catch (IllegalArgumentException e) {
            System.out.println("rejected: " + e.getMessage());
        }
        System.out.println("flexible constructors delete the static helper entirely");
    }
}

Flexible constructor bodies remove a workaround idiom without weakening initialisation safety.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 23 Course course, and every lesson in it is listed on the Java 23 Course contents page.