Static block initialization

前端 未结 3 1560
慢半拍i
慢半拍i 2021-01-19 05:19

This is a snippet of Java code:

static {        
    ture = 9;       
}
static int ture;
{ // instance block 
    System.out.println(\":\"+ture+\":\");              


        
3条回答
  •  半阙折子戏
    2021-01-19 05:46

    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.

提交回复
热议问题