Given example
interface A {
static int aInit() {
System.out.println("Interface field");
return 42;
}
int a = aInit();
}
class B implements A {
static int bInit() {
System.out.println("Class field");
return 42;
}
static final int b = bInit();
}
A a = new B();
on both JDK8 and JDK10 prints just "Class field"
. Direct access to A.a
spawns its initialization and "Interface field"
output.
This shows that interface static field initialization is lazy, which is not true for final static class field.
I can see OpenJDK JEP draft about such laziness for classes, but is it a documented feature for interface? Or just a detail of JVM implementation?
It is a documented behavior. The interface A
will not be initialized as per https://docs.oracle.com/javase/specs/jls/se12/html/jls-12.html#jls-12.4.1. It is only initialized when either the field a
or the method aInit()
are called.