gpt4 book ai didi

java - 阻止作用域输出

转载 作者:行者123 更新时间:2023-12-01 17:19:50 25 4
gpt4 key购买 nike

我不知道这个问题以前是否有人问过。我搜索过但找不到任何重复的问题。如果您发现任何相关问题,请提及链接。

public class Exp 
{
Exp()
{
System.out.println("Hello"); //3
}
{ System.out.println("Hello")}; //1
{ static{System.out.print("x");} //2
}

消息的打印顺序是2,1,3。

第 1 行和第 2 行的意义是什么以及为什么执行该命令

最佳答案

第“1”行是一个实例初始值设定项,它在首次创建对象时、调用任何构造函数之前运行。

第“2”行是一个静态初始值设定项,它在创建任何对象之前首次加载类时运行。

Section 12.5 of the JLS指定何时运行实例初始值设定项:

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:

Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.

If this constructor begins with an explicit constructor invocation (§8.8.7.1) of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.

This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.

Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.

Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.

(强调我的)

构造函数主体的其余部分在实例初始值设定项之后执行。

关于java - 阻止作用域输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19526649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com