我们可以将代码放入构造函数或方法或初始化块中。初始化块有什么用?每个Java程序都必须有它吗?
首先,有两种类型的初始化块:
public class Test { static int staticVariable; int nonStaticVariable; // Static initialization block: // Runs once (when the class is initialized) static { System.out.println("Static initalization."); staticVariable = 5; } // Instance initialization block: // Runs each time you instantiate an object { System.out.println("Instance initialization."); nonStaticVariable = 7; } public Test() { System.out.println("Constructor."); } public static void main(String[] args) { new Test(); new Test(); } }
印刷品:
Static initalization. Instance initialization. Constructor. Instance initialization. Constructor.
如果要运行某些代码而不管使用哪个构造函数,或者想要对匿名类进行一些实例初始化,则实例迭代块很有用。