GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev โ Flexible constructor bodies | java.evolved
Language
Intermediate
Flexible constructor bodiesValidate and compute values before calling super() or this(). Code Comparison
โ Java 8
class Square extends Shape {
Square(double side) {
super(side, side);
// can't validate BEFORE super!
if (side <= 0)
throw new IAE("bad");
}
}
โ Java 25+
class Square extends Shape {
Square(double side) {
if (side <= 0)
throw new IAE("bad");
super(side, side);
}
}
See a problem with this code? Let us know.
Why the modern way wins
๐ก๏ธ
Fail fastValidate arguments before the superclass constructor runs. ๐งฎ
Compute firstDerive values and prepare data before calling super(). ๐งน
No workaroundsNo more static helper methods or factory patterns to work around the restriction. Old Approach
Validate After super()
Modern Approach
Code Before super()
Since JDK
25
Difficulty
Intermediate
JDK Support
Flexible constructor bodies
Available
Finalized in JDK 25 LTS (JEP 513, Sept 2025). How it works
Java 25 lifts the restriction that super() must be the first statement. You can now validate arguments, compute derived values, and set up state before delegating to the parent constructor. Related Documentation
Proof
Related patterns
Language
Beginner
Type inference with varJava 8
Map<String, List<Integer>> map =
new HashMap<String, List<Integer>>();
for (Map.Entry<String, List<Integer>> e
: map.entrySet()) {
// verbose type noise
}
Java 10+
var map = new HashMap<String, List<Integer>>();
for (var entry : map.entrySet()) {
// clean and readable
}
JDK 10+
โ
Language
Beginner
Text blocks for multiline stringsJava 8
String json = "{\n" +
" \"name\": \"Duke\",\n" +
" \"age\": 30\n" +
"}";
Java 15+
String json = """
{
"name": "Duke",
"age": 30
}""";
JDK 15+
โ
Language
Beginner
Switch expressionsJava 8
String msg;
switch (day) {
case MONDAY:
msg = "Start";
break;
case FRIDAY:
msg = "End";
break;
default:
msg = "Mid";
}
Java 14+
String msg = switch (day) {
case MONDAY -> "Start";
case FRIDAY -> "End";
default -> "Mid";
};
JDK 14+
โ
|
| You are visitor 01402520 โ GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800ร600. No cookies required. |