0
package ali;

public class test {
public static int n = 99;

public static test t1 = new test("t1");
public static test t2 = new test("t2");

public static int i = 0;
public static int j = i;
{
    System.out.println("construct block");
}

static {
    System.out.println("static construct block");
}

public test(String str){
    System.out.println((++j) + ":" + "  i="+ i + "  n="+n+str);
    n++;i++;
}

public static void main(String [] args){
    test test1 = new test("initl");
}
}

after running:

construct block
1:  i=0  n=99t1
construct block
2:  i=1  n=100t2
static construct block
construct block
1:  i=0  n=101initl

Who can tell me how it works? why there is no "static construct block" when t1 and t2 ware created? why i and j changed to the default ,but n still unchanged?

Konstantin V. Salikhov
  • 4,554
  • 2
  • 35
  • 48
zawdd
  • 311
  • 1
  • 3
  • 12
  • possible duplicate of [Creating object using static keyword in Java](http://stackoverflow.com/questions/24927401/creating-object-using-static-keyword-in-java) – Konstantin V. Salikhov Aug 29 '14 at 06:07

2 Answers2

5

static variables/blocks are executed/initialized as they appear (usually).

your output and why? :

When the class is loaded and during its initialization, the following lines will be executed

public static test t1 = new test("t1");
public static test t2 = new test("t2");

which in-turn create new Test objects, but since the class is already under initialization, the above lines are not executed again.

So,

you get

construct block
1:  i=0  n=99t1
construct block
2:  i=1  n=100t2

Next, the static block executes

static construct block

Now when you create an object of Test in main(), you will have

construct block
1:  i=0  n=101initl
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • I know your mean,the first time t1 was created, – zawdd Aug 29 '14 at 06:33
  • public static int i = 0; public static int j = i; will be executed, and the when t2 is creating, the two lines won't executed again. but why when test1 create those two lines executed again?(cause i and j changed to default value) This is what I don't understand. – zawdd Aug 29 '14 at 06:36
  • The `public static int` lines are not executed when t1 or t2 is created at all. As they are static, they are executed, when the class file is loaded. Static fields and methods are not related with object instances at all and should not be linked to anything like "when instance created". – Korashen Aug 29 '14 at 06:49
  • When I try "public static int i = 3;"then I know that when “new test(t?) ” i and j the t? using, are default value 0.Thank you for your help! – zawdd Aug 29 '14 at 07:45
2

When this class (which really should have a capitalized name) is loaded, the static initializers are invoked in the order in which they appear in the source code. This means that the new test("t?") object creations happen before the explicit static block.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152