gpt4 book ai didi

Java - 将实例变量传递给 this() 方法

转载 作者:行者123 更新时间:2023-12-02 09:15:04 24 4
gpt4 key购买 nike

我正在学习如何使用 this() 调用重载的构造函数并遇到此限制:

You can not use any instance variable of the constructor's class in a call to this()

例如:

class Test{
int x;

public Test() {
this(x); //Does not compile
}

public Test(int y) {}

void method1() {
method2(x); //OK
}

void method2(int y) {}
}

我知道不需要将实例字段传递给构造函数,因为它默认是可见的。但是,为什么相同的限制没有应用于实例方法?

最佳答案

Java 中还有一个要求:构造函数调用(使用 this() 必须在任何构造函数中首先执行。构造函数将初始化对象。

之后,实例字段在这些初始调用后被初始化。因此,由于字段值现在已明确定义,因此您可以将它们用于任何用途,包括调用其他方法。

但是,在初始构造函数调用之前,这些字段处于未定义状态,不能用作其他构造函数调用的参数。

<小时/>

对于这些类型的事情,您需要在 JLS 中查找:

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

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

因此,实例变量仅在构造函数调用之后初始化。这是有道理的,因为首先为其分配默认值(零或 null),然后从构造函数中为其分配另一个值会很奇怪。

关于Java - 将实例变量传递给 this() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58895125/

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