繁体   English   中英

初始化程序块的不可预测的行为

[英]Unpredictable behaviour of an initializer block

public class Ex14 {
    static String strDef = "At the point of definition";
    static String strBlock;
    { strBlock = "In a block";}

    public static void main (String [] args){       
        System.out.println(Ex14.strDef);
        System.out.println(Ex14.strBlock);
        Ex14 test = new Ex14();
        System.out.println(test.strBlock);
        System.out.println(Ex14.strBlock);
    }

}

结果:

$ java Ex14
At the point of definition
null
In a block
In a block

如果我用注释的块切换块,则会打印两个语句。 换句话说,我只是

好吧,我无法理解这里发生了什么。

问题:

  1. 在初始化程序块内,变量是非静态的。 如果它没有与 static 声明混在一起,为什么编译器甚至没有警告我?

  2. 创建实例时,strBlock 不再是 null。 我无法理解为什么?

  3. 无论如何,我在这里什么都看不懂。 拜托,你能以某种方式澄清它吗?

  1. 在初始化程序块内,变量是非静态的。 如果它没有与 static 声明混在一起,为什么编译器甚至没有警告我?

不,变量仍然是static 您只是为 static 变量分配了一个新值。

  1. 创建实例时,strBlock 不再是 null。 我无法理解为什么?

实例初始化程序被内联到构造函数中,在对super(...)的(隐式或显式)调用和主体的 rest 之间。 你在这里拥有的相当于:

public class Ex14 {
    static String strDef = "At the point of definition";
    static String strBlock;

    public Ex14() {  // Default constructor.
      super(); // Implicit super constructor invocation.

      // Inlined instance initializer.
      Ex14.strBlock = "In a block";

      // Rest of the constructor body (there is none for a default ctor).
    }

    public static void main (String [] args){ 
      // ...
    }
 }

所以,在创建实例之前, Ex14.strBlock = "In a block"; 语句没有执行,所以它的值为null 创建实例(并因此执行构造函数)后, Ex14.strBlock已被重新分配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM