Interface Initialization Does Not Initialize Superinterfaces

huangapple go评论67阅读模式
英文:

Interface Initialization Does Not Initialize Superinterfaces

问题

The jj=4 is printed because when you access K.j, it triggers the initialization of the K interface. Since K extends J, it also initializes the fields from J, which includes int jj = Test.out("jj", 4);. That's why you see jj=4 printed in the output.

英文:

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?

答案1

得分: 1

如果JVM需要初始化接口,则它将对接口中的所有初始化进行操作,而不仅仅是您正在访问的变量。

在这种情况下,它不需要初始化I,因为它在其中使用的是一个常量字段,这不会触发初始化,但是它需要初始化J,因为它在使用j,它不是一个编译时常量表达式。这样做意味着两个变量都会被初始化。

英文:

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.

答案2

得分: 0

Compiler将K.j转换为J.j。所以在你的代码中没有对K的实际引用。

你在输出中看不到ii=2,因为在System.out.println(J.i);中,I.i的值被内联,所以没有对I的引用在你的代码中。

英文:

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.

huangapple
  • 本文由 发表于 2020年8月12日 18:47:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63374935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定