为什么实例初始化块在构造函数之前执行 [英] Why are instance initialization blocks executed before constructors

查看:107
本文介绍了为什么实例初始化块在构造函数之前执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道静态块是在加载类时初始化的,并且由于该类在程序中仅加载一次,因此它们仅被初始化一次。

I know that static blocks are initialized at the time the class is loaded and since the class is loaded only once in a program,they are initialized only once.

每次创建该类的实例时都会初始化IIB(实例初始化块),构造函数也是如此:它们在对象创建期间执行。

IIB (Instance initialization blocks) are initialized every time an instance of the class is made, and the same for constructors: they are executed during object creation.

我不了解为什么在下面的程序IIB中优先于构造函数执行。
代码-

I don't understand why in the below program IIB is executed in prior to Constructors. Code-

public class Hello {

    public static void main(String args[]) {
        C obj = new C();
    }
}

class A {

    static {
        System.out.println("Inside static block of A");
    }

    {
        System.out.println("Inside IIB of A");
    }

    A() {
        System.out.println("Inside NO-ARGS constructor of A");
    }
}

class B extends A {

    static {
        System.out.println("Inside static block of B");
    }

    {
        System.out.println("Inside IIB of B");
    }

    B() {
        System.out.println("Inside NO-ARGS constructor of B");
    }
}





class C extends B {

    static {
        System.out.println("Inside static block of C");
    }

    {
        System.out.println("Inside IIB of C");
    }

    C() {
        System.out.println("Inside NO-ARGS constructor of C");
    }
}

为什么与构造函数相比,首先执行IIB? p>

Why IIB is executed first compared to constructors?

推荐答案

Java编译器注入初始化程序块在您的构造函数的开头(在调用超级构造函数之后)。为了使您更好地理解,我编译了以下类

Java compiler injects initializer blocks at the beginning of your constructors (after calling a superconstructor). To give you a better understanding I've compiled the following class

public class Foo extends SuperFoo {
    private String foo1 = "hello";
    private String foo2;
    private String foo3;
    {
        foo2 = "world";
    }
    public Foo() {
        foo3 = "!!!";
    }
}

并通过 javap 反编译器:

and run it through a javap decompiler:

Compiled from "Foo.java"
public class Foo extends SuperFoo {
  private java.lang.String foo1;
  private java.lang.String foo2;
  private java.lang.String foo3;
  public Foo();
    Code:
       0: aload_0
       1: invokespecial #12                 // Method SuperFoo."<init>":()V
       4: aload_0
       5: ldc           #14                 // String hello
       7: putfield      #16                 // Field foo1:Ljava/lang/String;
      10: aload_0
      11: ldc           #18                 // String world
      13: putfield      #20                 // Field foo2:Ljava/lang/String;
      16: aload_0
      17: ldc           #22                 // String !!!
      19: putfield      #24                 // Field foo3:Ljava/lang/String;
      22: return
}

这篇关于为什么实例初始化块在构造函数之前执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆