gpt4 book ai didi

java - 为什么实例初始化 block 在构造函数之前执行

转载 作者:搜寻专家 更新时间:2023-10-31 19:54:16 28 4
gpt4 key购买 nike

我知道静态 block 是在加载类时初始化的,因为类在程序中只加载一次,所以它们只初始化一次。

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

我不明白为什么在下面的程序中 IIB 在构造函数之前执行。代码-

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 比构造函数先执行?

最佳答案

Java 编译器注入(inject)初始化 block at the beginning of your constructors (在调用超构造函数之后)。为了让您更好地理解,我编写了以下类(class)

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

并通过 javap 运行它 反编译器:

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
}

关于java - 为什么实例初始化 block 在构造函数之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31101110/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com