java初始化块执行顺序

java

  • java中初始化块的执行顺序在构造器之前,多个初始化块之间定义在前的先执行。如下:

public class InitialBlockTest {

// The first one

{

System.out.println("The first initial block");

}

// The second one

{

System.out.println("The second initial block");

}

// The constructor

public InitialBlockTest() {

System.out.println("Constructor of this class without any parameters");

}

public static void main(String args[]) {

new InitialBlockTest();

}

// The third one

{

System.out.println("The third initial block");

}

}

 结果如下:

The first initial block
The second initial block
The third initial block
Constructor of this class without any parameters

  • 类中声明变量指定初始值也是初始化代码,与初始化块相比,其执行顺序由定义先后决定。

public class InitTest {

{

a = 6;

}

int a = 9;

public static void main(String args[]) {

System.out.println(new InitTest().a);

}

}

 结果为:9

程序先为变量a分配内存,接着对其初始化。由于初始化块在前故先执行代码{ a = 6 },再执行

a = 9; 故a的值为9。

  • 与构造器一样,创建一个java对象时,不仅会执行该类的初始化块和构造器,而且会一直上溯到Object类。如下:

public class Test {

public static void main(String args[]) {

new Xiaomi();

}

}

class Phone {

{

System.out.println("Initial block in class Phone");

}

public Phone() {

System.out.println("Constructor of Phone");

}

}

class Xiaomi extends Phone {

{

System.out.println("Initial block in class Xiaomi");

}

public Xiaomi() {

System.out.println("Constructor of Xiaomi");

}

}

 结果为:

Initial block in class Phone
Constructor of Phone
Initial block in class Xiaomi
Constructor of Xiaomi

  •  静态初始化块是由static修饰的初始化块,属于类的静态成员。通常用于对类变量执行初始化处理,系统在类初始化

阶段执行静态初始块。如下:

public class Test {

public static void main(String args[]) {

new Xiaomi();

new Xiaomi();

}

}

class Phone {

static {

System.out.println("Static block of Phone");

}

{

System.out.println("Block of Phone");

}

public Phone() {

System.out.println("Constructor of Phone");

}

}

class Xiaomi extends Phone {

static {

System.out.println("Static block of Xiaomi");

}

{

System.out.println("Block of Xiaomi");

}

public Xiaomi() {

System.out.println("Constructor of Xiaomi");

}

}

 结果如下:

Static block of Phone
Static block of Xiaomi
Block of Phone
Constructor of Phone
Block of Xiaomi
Constructor of Xiaomi


Block of Phone
Constructor of Phone
Block of Xiaomi
Constructor of Xiaomi

类初始化阶段先执行最顶层父类的静态初始化块,然后依次向下,直到当前类的静态初始化块。

对象初始化阶段先执行最顶层父类的初始化块与构造器,一次向下,直到当前类的初始化块与构造器。

第一次创建Xiaomi对象时,因为系统还不存在Xiaomi类,因此需要加载初始化Xiaomi类,会先执行其顶层父类的静态初始化块。

一旦Xiaomi类初始化成功后,其后创建Xiaomi对象则不需要执行静态初始化块。

以上是 java初始化块执行顺序 的全部内容, 来源链接: utcz.com/z/392264.html

回到顶部