非静态初始化程序块如何调用? [英] How non-static initializer block invoked?

查看:111
本文介绍了非静态初始化程序块如何调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class A{

    {
        System.out.println("hi i am IIB");
    }

    public A(){
        System.out.println("hi i am constructor");
    }

    public static void main(String... args){
        A objA=new A();
    }

}

推荐答案

iib将在调用构造函数之前得到执行

iib will get execute before the constructor is called

不,这不会发生. 实例初始化程序块中编写的代码仅在运行时才是构造函数的一部分.在编译时,编译器将实例初始化程序块的代码移动到类的所有构造函数中.因此,在运行时,构造函数实际上等效于:

No, this is not what happens. The code written in instance initializer blocks are a part of the constructor only at runtime. At compile time, the compiler moves the code of the instance initializer blocks to all the constructors of your class. So, at runtime, the constructor is effectively equivalent to:

public A() {
    super();
    System.out.println("hi i am IIB"); 
    System.out.println("hi i am constructor");
}

因此,实例初始化程序块中的语句在存在该语句之前已移至构造函数.

So, the statement in the instance initializer block is moved to the constructor before the statement already there.

这是构造函数的实际外观(javap命令的输出):

Here's what the constructor looks like actually (Output of javap command):

 public A();
   Code:
      0: aload_0
      1: invokespecial #1    // Method java/lang/Object."<init>":()V
      4: getstatic     #2    // Field java/lang/System.out:Ljava/io/PrintStream;
      7: ldc           #3    // String hi i am IIB
      9: invokevirtual #4    // Method java/io/PrintStream.println:(Ljava/lang/String;)V
     12: getstatic     #2    // Field java/lang/System.out:Ljava/io/PrintStream;
     15: ldc           #5    // String hi i am constructor
     17: invokevirtual #4    // Method java/io/PrintStream.println:(Ljava/lang/String;)V
     20: return

这篇关于非静态初始化程序块如何调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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