Why is this an issue?

Java 25 introduces Flexible Constructor Bodies, which allow statements to be placed before an explicit constructor invocation - the super(…​) or this(…​) call. This enables developers to perform validation logic in the prologue, ensuring that the system avoids the overhead of initializing a superclass or allocating resources for an invalid object.

How to fix it

Move all the validation logic for parameters in a constructor before super(…​) or this(…​) call.

Code examples

Noncompliant code example

public class Coffee {
    int water;
    int milk;

    public Coffee(int water, int milk) {
        this.water = water;
        this.milk = milk;
    }
}

public class SmallCoffee extends Coffee {
    private static final int MAX_CUP_VOLUME = 100;
    int topping;

    public SmallCoffee(int water, int milk, String topping) {
        super(water, milk); // Noncompliant: constructing before validation
        int totalVolume = water + milk;
        if (totalVolume > MAX_CUP_VOLUME) {
            throw new IllegalArgumentException();
        }
        this.topping = topping;
    }
}

Compliant solution

public class SmallCoffee extends Coffee {
    private static final int MAX_CUP_VOLUME = 100;
    int topping;

    public SmallCoffee(int water, int milk, String topping) {
        int totalVolume = water + milk;
        if (totalVolume > MAX_CUP_VOLUME) {
            throw new IllegalArgumentException();
        }
        super(water, milk); // Compliant: validation before construction
        this.topping = topping;
    }
}

Resources