When is an interface with a default method initialized?

前端 未结 4 1780
失恋的感觉
失恋的感觉 2020-11-30 18:18

While searching through the Java Language Specification to answer this question, I learned that

Before a class is initialized, its direct superclass m

4条回答
  •  没有蜡笔的小新
    2020-11-30 18:41

    The interface is not initialized because the constant field InterfaceType.init , which is being initialized by non constant value (method call), is not used anywhere.

    It is known at compile time that constant field of interface is not used anywhere, and the interface is not containing any default method (In java-8) so there is no need to initialize or load the interface.

    Interface will be initialized in following cases,

    • constant field is used in your code.
    • Interface contains a default method (Java 8)

    In case of Default Methods, You are implementing InterfaceType. So, If InterfaceType will contain any default methods, It will be INHERITED (used) in implementing class. And Initialization will be into the picture.

    But, If you are accessing constant field of interface (which is initialized in normal way), The interface initialization is not required.

    Consider following code.

    public class Example {
        public static void main(String[] args) throws Exception {
            InterfaceType foo = new InterfaceTypeImpl();
            System.out.println(InterfaceType.init);
            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();
    }
    

    In above case, Interface will be initialized and loaded because you are using the field InterfaceType.init.

    I am not giving the default method example as you already given that in your question.

    Java language specification and example is given in JLS 12.4.1 (Example does not contain default methods.)


    I can not find JLS for Default methods, there may be two possibilities

    • Java people forgot to consider the case of default method. (Specification Doc bug.)
    • They just refer the default methods as non-constant member of interface. (But mentioned no where, again Specification Doc bug.)

提交回复
热议问题