J.IX · Java 25 practice question
A developer is working with Java 25 and wishes to perform some logging or initialization logic in a subclass's constructor *before* calling the superclass constructor, using the feature allowing statements before `this()` or `super()`. Which of the following patterns correctly leverages this feature while maintaining proper inheritance chain initialization? Consider the following class structure:
class Parent {
public Parent() {
System.out.println("Parent constructor called.");
}
}
class Child extends Parent {
public Child() {
// Logic must happen here before Parent initialization, if possible.
// How should the body be structured?
// ...
}
}
Check answer and explanation
Correct answer: The custom logic can be placed before `super();`, provided it does not reference `this` or any instance members of the current class or its superclass.
Explanation
Java 25 introduces flexibility in constructor bodies, allowing statements to appear before `this()` or `super()`. However, even with this flexibility, the fundamental contract of object construction requires that the superclass's state be initialized before the subclass modifies or relies on that state. If the custom logic doesn't depend on parent initialization (e.g., it only logs or sets local state), it can come first. If it *does* depend on parent initialization, it must come after the call to `super()`. Therefore, the safest and correct pattern when using the new feature is to place non-dependent initialization before `super()`, but the rule must be that the logic cannot assume parent initialization has occurred.
Common trap
Option C represents the traditional pattern that this new feature aims to sometimes bypass, but it is only strictly necessary if the logic depends on the parent's state. Option A is incorrect because the new feature allows movement of code.
Source: Java Language Specification - Preview Feature JEP 513 (General reference, as specific JEP 513 details might evolve) - https://openjdk.org/jeps/513
Checked against the cited text on 2026-11-27.