Reputation: 59
I found this code here, precisely Example 12.4.1-3. Interface Initialization Does Not Initialize Superinterfaces
, a bit below of given address.
interface I {
int i = 1, ii = Test.out("ii", 2);
}
interface J extends I {
int j = Test.out("j", 3), jj = Test.out("jj", 4);
}
interface K extends J {
int k = Test.out("k", 5);
}
class Test {
public static void main(String[] args) {
System.out.println(J.i);
System.out.println(K.j);
}
static int out(String s, int i) {
System.out.println(s + "=" + i);
return i;
}
}
And the answer is:
1
j=3
jj=4
3
Question is: How is jj=4
is printed?
Upvotes: 2
Views: 215
Reputation: 34618
If the JVM needs to initialize the interface, then it will do all the initializations in the interface, not just the variable you were accessing.
In this case, it didn't need to initialize I
because it was using a constant field in it, which does not trigger initialization, but it did need to initialize J
because it was using j
, which is not a compile-time constant expression. Doing that means both variables get initialized.
Upvotes: 1
Reputation: 20455
Compiler convert K.j
into J.j
. So no actual reference to K
in your code.
You don't see ii=2
in your output because in System.out.println(J.i);
value of I.i
get inlined so no reference to I
in your code.
Upvotes: 0