在Java中使用static关键字创建对象
class abc {
int a = 0;
static int b;
static abc h = new abc(); //line 4
public abc() {
System.out.println("cons");
}
{
System.out.println("ini");
}
static {
System.out.println("stat");
}
}
public class ques {
public static void main(String[] args) {
System.out.println(new abc().a);
}
}
当我写这段代码时,我按顺序输出像这样:
When i wrote this code I am getting output in order like this:
ini
cons
stat
ini
cons
0
这时我在 main()中创建了一个新对象, class abc
已加载, static
变量和块按写入顺序执行。当控制进入第4行 static abc h = new abc();
调用实例初始化块。为什么?为什么在第4行创建一个新对象时没有调用静态块,直到那时静态块也没有被调用一次,所以根据惯例静态块应该被调用。为什么会出现意外输出?
Here when I created a new object in main(), class abc
got loaded and static
variables and blocks are executed in order they are written. When control came to line 4 static abc h = new abc();
Instance Initialization block is called. Why? why is static block not called when a new object is created at line 4 and till that time static block was also not called even once, so according to convention static block should have been called. Why is this unexpected output coming?
静态字段初始化和静态块按声明的顺序执行。在您的情况下,代码在分离声明和初始化后等效于此:
Static fields initialization and static blocks are executed in the order they are declared. In your case, the code is equivalent to this after separating declaration and initialization:
class abc{
int a;
static int b;
static abc h;//line 4
static {
h = new abc();//line 4 (split)
System.out.println("stat");
}
public abc() {
a = 0;
System.out.println("ini");
System.out.println("cons");
}
}
public class ques{
public static void main(String[] args) {
System.out.println(new abc().a);
}
}
所以当你从你的代码到达第4行时,静态初始化实际上正在执行但尚未完成。因此,在 stat
可以打印之前调用构造函数。
So when you reach line 4 from your code, the static initialization is actually being executed and not finished yet. Hence your constructor is called before stat
can be printed.