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 methodsarrow-up-right, it is considered bad practice: Item 19 of Effective Java (Third Edition)arrow-up-right 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:

There are two cases :

  • simple validation before calling super

  • list of illegal this references during class creation

    • special cases with inner classes

Last updated