gpt4 book ai didi

java - 如果构造函数没有任何返回类型,它如何返回?

转载 作者:行者123 更新时间:2023-11-29 06:58:15 24 4
gpt4 key购买 nike

这似乎是一个令人困惑的问题。根据定义,我知道构造函数是一种特殊类型的方法,用于初始化对象的状态和/或为实例变量赋值。

Stack Overflow 中也有人提到构造函数返回一个类的对象(实例),这与普通方法的作用/返回相反?

尽管查阅了大量教程和引用资料,但我找不到关于构造函数如何能够在不存在 return 语句的情况下返回值的具体原因。

我很想知道整个过程的内部工作原理。

最佳答案

构造器不返回任何东西。构造函数只是初始化一个实例。

A new instance creation expression

new SomeExample();

产生对指定类的新实例的引用

A new class instance is explicitly created when evaluation of a class instance creation expression (§15.9) causes a class to be instantiated.

并调用相应的构造函数来初始化创建的实例

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

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