什么是初始化块?我们可以将代码放入构造函数、方法或初始化块中。初始化块的用途是什么?每个java程序都必须拥有它吗?
3 回答
MMTTMM
TA贡献1869条经验 获得超4个赞
实例初始化块
,和 静态初始化块.
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.
墨色风雨
TA贡献1853条经验 获得超6个赞
public class StaticTest extends parent { static { System.out.println("inside satic block"); } StaticTest() { System.out.println("inside constructor of child"); } { System.out.println("inside initialization block"); } public static void main(String[] args) { new StaticTest(); new StaticTest(); System.out.println("inside main"); }}class parent { static { System.out.println("inside parent Static block"); } { System.out.println("inside parent initialisation block"); } parent() { System.out.println("inside parent constructor"); }}
inside parent Static block inside satic block inside parent initialisation block inside parent constructor inside initialization block inside constructor of child inside parent initialisation block inside parent constructor inside initialization block inside constructor of child inside main
添加回答
举报
0/150
提交
取消