Java 22 brings forth a new preview language feature: the ability to include statements before the super()
call in constructors.
Traditionally, Java constructors have had a strict rule: the super()
call, which invokes the superclass constructor, must always be the first statement in a subclass constructor. This rule, while ensuring proper initialisation order, sometimes led to verbose or convoluted constructor implementations, especially when additional setup was required before invoking the superclass constructor.
With the introduction of JDK 22, this limitation has been relaxed with the introduction of pre-super statements, which allow you to validate and prepare arguments before the super()
call. This also facilitates fail-fast scenarios, because you can perform rigorous argument validation or exception handling before superclass instantiation.
Here is an example:
class Shape { private final String color; Shape(String color) { this.color = color; } } class Rectangle extends Shape { private final double length; private final double width; Rectangle(String color, double length, double width) { if (length <= 0 || width <= 0) { throw new IllegalArgumentException("Dimensions must be positive"); } super(color); this.length = length; this.width = width; } }
In this example, before invoking the superclass constructor, a pre-super statement validates the dimensions of the rectangle, ensuring they are positive.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.