本文介绍了java中的内联初始化块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级

public class MyMain{
    public static void main(String... arg){
            Temp t = new Temp(){
                {
                    System.out.println(" instance initialize");
                }
            };

        }
    }

class Temp{
    int i;

    {
        i=9;
        System.out.println("Static"+i);
    }
    Temp(){
        System.out.println("Temp const "+i);
    }
}

当我执行main方法时输出到:

When i execute the main method the output comes:

Static9
Temp const 9
instance initialize

理想情况下,块在构造函数之前执行,但是在构造函数之后调用内联初始化块。为什么?

Ideally, the blocks are executed before the constructor, but the inline initialization block is called after the Constructor. Why?

推荐答案

您正在创建 Temp的子类 。对于每个类,任何实例初始值设定项都在构造函数体之前执行 - 但是超类在子类初始化之前进行初始化。所以执行流程为:

You're creating a subclass of Temp. For each class, any instance initializers are executed before the constructor body - but the superclass goes through initialization before the subclass initialization. So the execution flow is:


  • 对象
  • $ b中的初始值设定项$ b
  • 对象中的构造函数体

  • Temp
  • 构造函数体 Temp

  • 匿名类中的初始值设定项

  • 匿名类中的构造函数体(无)

  • Initializers in Object
  • Constructor body in Object
  • Initializers in Temp
  • Constructor body in Temp
  • Initializers in anonymous class
  • Constructor body in anonymous class (none)

我强烈建议您重构任何看起来像这样的代码 - 目标为了清晰而不是聪明。

I would strongly advise you to refactor any code which looked like this anyway - aim for clarity rather than cleverness.

这篇关于java中的内联初始化块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:59