gpt4 book ai didi

java - 会 this.method2();跳过返回值?

转载 作者:行者123 更新时间:2023-11-30 02:52:49 30 4
gpt4 key购买 nike

在此代码示例中。 “this.method2();”之后会读到什么?在返回returnedValue之前会跳转到method2()吗?

public int method1(int returnedValue) {
// Do something
returnedValue = 1;
this.method2(); // Where will it go after this line?
return returnedValue;
}

public void method2() {
// Do something
}

public static void main(String[] args) {
sp.method2();
Stuff sp = new Stuff();
System.out.print(returned value);
}

最佳答案

现在你的 main 方法不调用 method1,请考虑这个 main 方法:

public static void main(String[] args) { new Main().method1();}

假设Main是主类,这一行会发生什么:

this.method2();

是否在 method1 返回值之前调用了 method2,因为在调用 method2 之前没有调用 return

如果 method1 是这样定义的:

public void method1(int returnedvalue)
{
returnedvalue=1;
return returnedvalue;
this.method2();
}

然后method1将返回returnedvalue而不调用method2(上面的代码当然不好,因为this.method2()无法访问)。

method2完成并返回后,method1执行下一条语句return returnedvalue,它将返回并在main中继续执行。

当然,正如其他人所说,如果在 method2 中引发异常但没有被捕获,异常将从 method2 传播到 method1,如果 method1 没有捕获它,它将传播到 main,如果 main 没有捕获它,你的应用程序将崩溃:)。

关于java - 会 this.method2();跳过返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38124563/

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