gpt4 book ai didi

java - 类加载时进行的调用

转载 作者:行者123 更新时间:2023-12-02 11:17:33 25 4
gpt4 key购买 nike

public class SuperClass{
public SuperClass(){
System.out.println("Super class");
}
}

public class SubClass extends SuperClass{
int i;
{
i=10;
}
public SubClass(){
System.out.println("Subclass");
}
public static void main(String[] args){
SubClass sc = new SubClass();
}
}

我对所有可能的地方进行了调试,我发现首先创建实例时,它首先进入 SuperClass 构造函数并打印 Super Class,然后才进入实例变量,然后是初始化 block ,最后是 SubClass构造函数并打印子类。

但是,我在某处读到,子类构造函数内部默认调用 super() 的地方,也就是它进入父类(super class)构造函数的时候!!!

最佳答案

SubClass() 构造函数隐式如下所示:

 public SubClass(){
super();
{
i=10;
}
System.our.println("Subclass");
}

根据 JLS section 12.5 :

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:

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

  2. 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.

  3. 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.

  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.

  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/17022389/

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