Static block initialization

三世轮回 提交于 2019-12-01 20:45:10
T.J. Crowder

Regarding your first question, static blocks are indeed processed in the order in which they appear, but declarations are processed first, before the static blocks are. Declarations are processed as part of the preparation of the class (JLS §12.3.2), which occurs before initialization (JLS §12.4.2). For learning purposes, the entire JLS §12 may be useful, as well as JLS §8, particularly §8.6 and JLS §8.7. (Thank you to Ted Hopp and irreputable for calling out those sections.)

There isn't enough information in your quoted code to answer your second question. (In any case, on SO it's best to ask one question per question.) But for instance:

public class Foo {
    static {     
        ture = 9;   
    }

    static int ture;

    {   // instance block   
        System.out.println(":"+ture+":");

    }

    public static final void main(String[] args) {
        new Foo();
    }
}

...only outputs :9: once, because only one instance has been created. It doesn't output it at all if you remove the new Foo(); line. If you're seeing :9: three times, then it would appear that you're creating three instances in code you haven't shown.

The static initializers are executed in the order in which they appear and the declarations aren't executed at all, that's how they got their name. This is why your code compiles without problems: the class structure is assembled at compile time from the declarations, and the static blocks are executed at runtime, long after all the declarations have been processed.

As others have said, the place of declaration is generally inconsequential.

But sometimes it may cause confusions:

class Z {
    static int i = j + 2;  // what should be the value of j here?
    static int j = 4;
}

So Java does add some restrictions on forward reference: http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2.3

Your example is allowed because the usage of the field is on the left hand side of an assignment. Apparently the language designers don't think it's too confusing. Nevertheless we should probably always avoid forward reference if we can.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!