Typically, we create alternative solutions for tasks that are necessary, but not officially permitted. For instance, executing statements before super() in a derived class constructor was not officially allowed, even though it was important for, say, validating values being passed to the base class constructor. A popular workaround involved creating static methods to validate values and then calling these methods on the arguments of super(). Though this approach worked well, it could make the code look complicated. This is changing with Statements before super(), a preview language feature in Java 22.
By using this feature, you can opt for a more direct approach, that is, drop the workaround of creating static methods, and execute code that validates arguments, just before calling super(). Terms and conditions still apply, such as, not accessing instance members of a derived class before execution of super() completes.
I know you are wondering, why was this constraint added in the first place, how is this being resolved, does it change the internal JVM working, and the most important question – how can you benefit from this feature? I’ll answer all these questions in this blog post.