0

An interface with a default method is initialized even if this method is overridden and even if it's not at all invoked.

Example:

    public interface I {
    int a = foo();
     default void test1(){
     }
    static int foo(){
        System.out.println("I initialized");
        return 15;
    }
}


    public class C implements I{
     public void test2(){
          System.out.print("C initialized");
      }
}


    public class Test {
      public static void main(String[] args) {    
         C c = new C();
         c.test2();
      }   
}

prints:

I initialized
C initialized

What's exactly the problem here?

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
Hicham Moustaid
  • 773
  • 6
  • 13

1 Answers1

0

You've defined the field a; the compiler doesn't know that you never access it in the implementation. It must run the method to determine the value.

int a = foo(); // <-- must run foo.
static int foo(){
    System.out.println("I initialized"); // <-- prints I initialized 
    return 15;
}

and

a = 15

and test1 has nothing to do with test2, but even if it did foo() would still need to be evaluated to set a.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • But according to the JLS section 12.4.1, the invocation of test2 should initialize the class C and its superclasses but not its superinterfaces. – Hicham Moustaid Nov 14 '14 at 05:47
  • [JLS-12.4.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.1) and scroll down *Example 12.4.1-3. Interface Initialization Does Not Initialize Superinterfaces* and note that `i = 1` prints first (as in your question) and you don't have an interface K here. – Elliott Frisch Nov 14 '14 at 05:52
  • This is because a reference to a static field causes initialization of only the class or interface that actually declares it. – Hicham Moustaid Nov 14 '14 at 05:56
  • What problem are you trying to solve, and how does **this** help you solve it? – Elliott Frisch Nov 14 '14 at 05:58