Tuesday, 7 October 2025

Constructors - another way Java 25 can be subtly different

Constructors are still super - eventually 

Java 25 has introduced a change to the way that constructors work in the inheritance hierarchy.

In previous versions of Java, if we have a class that extends another class then all constructors of the subclass have to either specify a constructor from the base class as the first operation or automatically have the default zero arguments constructor applied by default - or call on alternate constructor and get the subclass's constructor invoked via that.

In Java 25 it is now valid to call super() later in the constructor.

So, we could have the following as valid code...

public class SomeBaseClass {
SomeBaseClass() {
System.out.println("Hello from SomeBaseClass constructor");
}
}

public class SomeSubClass extends SomeBaseClass {
SomeSubClass() {
System.out.println("Hello from SomeSubClass constructor");

super();
}
}


public class ConstructorDemo {
static void main() {
SomeSubClass someSubClass = new SomeSubClass();
}
}
 
The output from running ConstructorDemo would be:
Hello from SomeBaseClass constructor
Hello from SomeSubClass constructor

In older versions of Java we would have gotten a compilation error for the SomeSubClass constructor.

See https://openjdk.org/jeps/513 for the details.

It makes sense for validation and similar use cases, but could trigger a few sideways glances from developers reviewing pull requests.

No comments:

Post a Comment

A time for cool heads