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.

有帮助吗?

解决方案

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归因
不隶属于 StackOverflow
scroll top