简体   繁体   English

构造函数被“调用”与构造函数“被执行”?

[英]Constructor is “invoked” vs. Constructor is “executed”?

What is the difference betweeen constructor invocation and constructor execution? 构造函数调用和构造函数执行之间有什么区别? I am reading about constructor order dependecies from java programming langauage by james Gosling.The author states that when you create an object constructor is first invoked, then feild members are intialized finally costructor is executed.Both sounds the same to me. 我正在阅读james Gosling的java编程语言中的构造函数顺序依赖。作者指出,当你创建一个对象构造函数时,首先调用,然后使用feild成员进行初始化,最后执行costructor.Both听起来和我一样。

In that context, "invoked" is when you call it, and "executed" is when the body of code is actually run . 在这种情况下,“调用”是指调用它时,“执行”是指代码体实际运行时

Between the time you call it and the time the code runs, the fields are initialized. 在您调用它和代码运行的时间之间,字段被初始化。

So, you invoke it, then initialization happens, then it is executed. 所以,你调用它,然后初始化发生, 然后执行。

Try this: 试试这个:

class Example {

    static int report() { System.out.println("initialize"); return 0; }

    int x = report(); // <- [Step 2] Initialization

    Example () {
        System.out.println("execute"); // <- [Step 3] Execution
    }

}

Then, elsewhere: 然后,在别处:

System.out.println("invoke");
new Example(); // <- [Step 1] Invocation

The output will be: 输出将是:

invoke
initialize
execute

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

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