Java 中的静态块和初始化程序块?

可能的复制品:
静态初始化块

考虑以下 密码:

public class Test {
{
System.out.println("Empty block");
}
static {
System.out.println("Static block");
}
public static void main(String[] args) {
Test t = new Test();
}
}

我们知道,首先执行 静电干扰块,然后执行 空荡荡的块。但问题是,我从来没有能够理解一个 空荡荡的块的真正实用性。有人能举个真实的例子吗

  • 正在使用 静电干扰空荡荡的
  • 静电干扰空荡荡的块都有不同的实用程序
71355 次浏览

They're for two very different purposes:

  • The static initializer block will be called on loading of the class, and will have no access to instance variables or methods. As per @Prahalad Deshpande's comment, it is often used to create static variables.
  • The non-static initializer block on the other hand is created on object construction only, will have access to instance variables and methods, and (as per the important correction suggested by @EJP) will be called at the beginning of the constructor, after the super constructor has been called (either explicitly or implicitly) and before any other subsequent constructor code is called. I've seen it used when a class has multiple constructors and needs the same initialization code called for all constructors. Just as with constructors, you should avoid calling non-final methods in this block.

Note that this question has been answered many times in stackoverflow and you would do well to search and review the similar questions and their answers. For example: static-initialization-blocks

The static block is executed whenever your class loads. The empty block is executed whenever you instantiate your class. Try comparing these:

1.

public static void main(String[] args) {
Test t = new Test();
}

2.

public static void main(String[] args) {


}

Outputs:

1.

Static block
Empty block

2.

Static block

In Layman words, static block only gets called once, no matter how many objects of that type you create.