无效并返回Java-何时使用 [英] Void and return in Java - when to use
问题描述
我对虚无和回报有些困惑".通常,我知道在方法中使用void而不返回任何内容,而当我想将某些内容返回给调用代码时,则在方法中使用return.
I have some "confusion" about void and return. In general, I understand void is used in methods without returning anything, and return is used in methods when I want to return something to the calling code.
但是在下面的代码中,我可以同时使用两者,而我的问题是,使用哪个?以及如何确定?与性能有关吗?
But in the following code, I can use both, and my question is, which one to use? And how to determine? Is it about performance?
通常,在两种情况下我的结果都是相同的.
Normally, I have the same results in both cases.
public class Calc {
private double number;
Calc (double n)
{
number = n;
}
public void add(double n)
{
number += n;
}
public double add1(double n)
{
return number = number + n;
}
}
谢谢!
推荐答案
此方法:
public void add(double n)
{
number += n;
}
您更改了 number
的内部状态,但是此方法的调用者不知道 number
的最终值.
You change the internal state of number
but the caller of this method doesn't know the final value of number
.
在下面的方法中,您将提示呼叫者 number
的最终值.
In the below method, you are intimating the caller the final value of number
.
public double add1(double n)
{
return number = number + n;
}
我建议保留一个单独的 getNumber()
getter方法.
I would suggest to keep a separate getNumber()
getter method.
这篇关于无效并返回Java-何时使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!