Runnable sources, broken examples and captured transcripts for the ankurm.com JEP 513 article, including the JDK 25 vs 27 compiler wording differences. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01TF9JWFvJSNm6HVzswzZU5a
37 lines
1.2 KiB
Java
37 lines
1.2 KiB
Java
// The classic superclass-constructor trap, and the fix JEP 513 makes possible.
|
|
public class OverridableCall {
|
|
static class Base {
|
|
Base() {
|
|
IO.println(" Base constructor calls describe(): " + describe());
|
|
}
|
|
String describe() { return "base"; }
|
|
}
|
|
|
|
// The bug: describe() runs from Base's constructor, before Broken's own field has been assigned.
|
|
static class Broken extends Base {
|
|
private final String label;
|
|
Broken(String label) {
|
|
super();
|
|
this.label = label;
|
|
}
|
|
@Override String describe() { return "label=" + label; }
|
|
}
|
|
|
|
// The fix: assign the field in the prologue, before super() runs Base's constructor.
|
|
static class Fixed extends Base {
|
|
private final String label;
|
|
Fixed(String label) {
|
|
this.label = label; // allowed in the prologue: a plain assignment to a field of THIS class
|
|
super();
|
|
}
|
|
@Override String describe() { return "label=" + label; }
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
IO.println("Broken (assign after super()):");
|
|
new Broken("hello");
|
|
IO.println("Fixed (assign before super()):");
|
|
new Fixed("hello");
|
|
}
|
|
}
|