Java interface static field lazy initialization

问题: Given example interface A { static int aInit() { System.out.println("Interface field"); return 42; } int a = aInit(); } class B implements A...

问题:

Given example

interface A {
    static int aInit() {
        System.out.println("Interface field");
        return 42;
    }
    int a = aInit();
}

class B implements A {
    static int bInit() {
        System.out.println("Class field");
        return 42;
    }
    static final int b = bInit();
}

A a = new B();

on both JDK8 and JDK10 prints just "Class field". Direct access to A.a spawns its initialization and "Interface field" output.

This shows that interface static field initialization is lazy, which is not true for final static class field.

I can see OpenJDK JEP draft about such laziness for classes, but is it a documented feature for interface? Or just a detail of JVM implementation?


回答1:

It is a documented behavior. The interface A will not be initialized as per https://docs.oracle.com/javase/specs/jls/se12/html/jls-12.html#jls-12.4.1. It is only initialized when either the field a or the method aInit() are called.

  • 发表于 2019-03-29 21:22
  • 阅读 ( 187 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除