While searching through the Java Language Specification to answer this question, I learned that
Before a class is initialized, its direct superclass must be initialized, but interfaces implemented by the class are not initialized. Similarly, the superinterfaces of an interface are not initialized before the interface is initialized.
For my own curiosity, I tried it and, as expected, the interface InterfaceType
was not initialized.
public class Example {
public static void main(String[] args) throws Exception {
InterfaceType foo = new InterfaceTypeImpl();
foo.method();
}
}
class InterfaceTypeImpl implements InterfaceType {
@Override
public void method() {
System.out.println("implemented method");
}
}
class ClassInitializer {
static {
System.out.println("static initializer");
}
}
interface InterfaceType {
public static final ClassInitializer init = new ClassInitializer();
public void method();
}
This program prints
implemented method
However, if the interface declares a default
method, then initialization does occur. Consider the InterfaceType
interface given as
interface InterfaceType {
public static final ClassInitializer init = new ClassInitializer();
public default void method() {
System.out.println("default method");
}
}
then the same program above would print
static initializer
implemented method
In other words, the static
field of the interface is initialized (step 9 in the Detailed Initialization Procedure) and the static
initializer of the type being initialized is executed. This means that the interface was initialized.
I could not find anything in the JLS to indicate that this should happen. Don't get me wrong, I understand that this should happen in case the implementing class doesn't provide an implementation for the method, but what if it does? Is this condition missing from the Java Language Specification, did I miss something, or am I interpreting it wrongly?