Static block initialization

This is a piece of Java code:

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

How does it compile at all? After initialization, the variable 'ture' was declared. As far as I know, static blocks and fields were executed in the order in which they appear.

Now why is this value of 9 in the instance block printed 3 times? By the way, an instance of the class was created 3 times. This is not homework; I am learning Java for certification.

+4
source share
3 answers

As for your first question, static blocks are actually processed in the order in which they appear, but declarations are processed first before static blocks. Declarations are processed as part of the class preparation ( JLS ยง12.3.2 ) that occurs before initialization ( JLS ยง12.4.2 ). For training purposes, the whole JLS ยง12 , as well as JLS ยง8 , in particular ยง8.6 and JLS ยง8.7, may be useful. (Thanks, Ted Hopp and irreputable for invoking these sections.)

There is not enough information in your cited code to answer the second question. (In any case, on SO, it is better to ask one question per question.) But, for example:

 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 prints once :9: since only one instance was created. It does not display it at all if you delete the line new Foo(); . If you see :9: three times, then it looks like you are creating three instances of code that you did not show.

+11
source

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

+2
source

As others have said, the place of the announcement is usually not significant.

But sometimes it can cause bewilderment:

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

So Java adds some restrictions for the direct link: http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2.3

Your example is allowed, since the use of the field is on the left side of the task. Apparently, the developers of the language do not find this too confusing. However, we can probably always avoid direct treatment if we can.

+2
source

All Articles