JEP 492: Flexible Constructor Bodies (Third Preview)
π What is it?
Traditionally, Java constructors have required explicit placement of super()
or this()
as the first line in the constructor.
JEP 492 relaxes this rule:
β‘οΈ Now, you can run code before calling super()
or this()
β as long as you donβt access this
or instance members before initialization.
Fixed calling subclass overriden method
Although the Java language allows constructors to invoke overridable methods, it is considered bad practice: Item 19 of Effective Java (Third Edition) advises that "Constructors must not invoke overridable methods." To see why it is considered bad practice, consider the following class hierarchy:
class Super {
Super() { overriddenMethod(); }
void overriddenMethod() { System.out.println("hello"); }
}
class Sub extends Super {
final int x;
Sub(int x) {
this.x = x; // Initialize the field
super(); // Then invoke the Super constructor explicitly
}
@Override
void overriddenMethod() { System.out.println(x); }
}
RUN:
FlexibleConstructorDemo
There are two cases :
simple validation before calling super
list of illegal this references during class creation
special cases with inner classes
Last updated