class Shape {
final int area;
public Shape(int area) {
if (area <= 0) throw new IllegalArgumentException("Area must be positive.");
this.area = area;
}
}
Agora diga que você quer ter um Rectangle aula. Em Java antes do JDK 25, você teria que extrair de alguma forma o cálculo para usá-lo no super() chamada, geralmente usando um método estático:
// The old way
class Rectangle extends Shape {
private static int checkAndCalcArea(int w, int h) {
if (w <= 0 || h <= 0) {
throw new IllegalArgumentException("Dimensions must be positive.");
}
return w * h;
}
public Rectangle(int width, int height) {
super(checkAndCalcArea(width, height)); // super() had to be first
// ... constructor logic ...
}
}
Este código é bastante desajeitado. Mas no Java 25 é mais fácil seguir sua intenção e executar o cálculo da área no Rectangle construtor:
class Rectangle extends Shape {
final int width;
final int height;
public Rectangle(int width, int height) {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Dimensions must be positive.");
}
int area = width * height;
super(area); // Before 25, this was an error
this.width = width;
this.height = height;
}
}
Importações de módulos no atacado
Outro recurso finalizado no JDK 25, JEP 511: Declarações de importação de módulo, permite importar um módulo inteiro em vez de ter que importar cada pacote um por um.
