Java 中的 void 和 return - 何时使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17527555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:13:22  来源:igfitidea点击:

Void and return in Java - when to use

javareturnvoid

提问by user2026884

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.

我对 void 和 return 有一些“困惑”。一般来说,我理解 void 用于不返回任何内容的方法中,而当我想向调用代码返回某些内容时,在方法中使用 return 。

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;
    }
}

Thank you!

谢谢!

回答by NINCOMPOOP

This method :

这种方法:

public void add(double n)
{
   number += n;
} 

You change the internal state of numberbut the caller of this method doesn't know the final value of number.

您更改了 的内部状态,number但此方法的调用者不知道 的最终值number

In the below method, you are intimating the caller the final value of number.

在下面的方法中,您向调用者暗示 的最终值number

public double add1(double n)
{
   return number = number +  n;
}

I would suggest to keep a separate getNumber()getter method.

我建议保留一个单独的getNumber()getter 方法。

回答by Marko Topolnik

Do you want to be able to write this?

你想能够写这个吗?

Calc c = new Calc();
double a = c.add(3);

If yes, then keep your add1method. A perhaps better way to utilize the return value in your kind of object is the following:

如果是,那么保留你的add1方法。在您的对象类型中利用返回值的一种可能更好的方法是:

public class Calc {
  ....
  public Calc add(double d) { number += d; return this; } 
}

Now you can write

现在你可以写

Calc c = new Calc().add(1).add(2);

which is many times very convenient, reads well, and conserves the vertical screen space.

很多时候非常方便,阅读效果很好,还节省了竖屏空间。

This idiom is called the fluent API.

这种习惯用法称为fluent API

回答by Mark Said Camilleri

In the void method:

在 void 方法中:

public void add(double n)
{
    number += n;
} 

You aren't able to use the nvariable across methods. This means that you won't be able to use it for the Calcmethod.

您无法n跨方法使用该变量。这意味着您将无法将它用于该Calc方法。

However, when using a method which actually returns something, like:

但是,当使用实际返回某些内容的方法时,例如:

public double add1(double n)
{
    return number = number +  n;
}

you get to use that variable as an object thus allowing you to use it within the Calcmethod and others as many times as you wish, each time might be the same object (not advised if using to calculate using different values) or a new object every time.

您可以将该变量用作对象,从而允许您根据需要在Calc方法和其他方法中多次使用它,每次都可能是同一个对象(如果使用不同的值进行计算,则不建议使用)或每个新对象时间。

As far as I know, there are no visible performances issues.

据我所知,没有明显的性能问题。

回答by Paul J Abernathy

I personally prefer to return a value. It allows you to give information to the calling code with little to no cost (performance is generally about the same either way). It can either be the result of the calculation or, as Mark mentioned, the object to allow you to chain statements together. Which one might depend on your specific application.

我个人更喜欢返回一个值。它允许您以很少甚至没有成本的方式向调用代码提供信息(两种方式的性能通常大致相同)。它可以是计算的结果,也可以是像 Mark 提到的那样,允许您将语句链接在一起的对象。哪一个可能取决于您的特定应用程序。

回答by Ashraf Abusada

returnshould not be used with void class type as the program output is returned by default and can be displayed through appropriate methods of the java class, like when you want to display the output of your program:

return不应与 void 类类型一起使用,因为程序输出默认返回并且可以通过 java 类的适当方法显示,例如当您想要显示程序的输出时:

System.out.println("number = " + number);

System.out.println("number = " + number);

回答by Botea Florin

you have function definition like this: -public(or private, etc)-lvl access. -static(or blank)to access that method without creating an instance of that object. -and void: you have noticed that any function that return something have that 'something's' data type included in definition (eg: returning int values, or strings). Now, when your function have no return, think at VOID like a placeholder for datatype(int,string, etc)

您有这样的函数定义:-public(或私有等)-lvl 访问。-静态(或空白)访问该方法而不创建该对象的实例。- 和无效:您已经注意到,任何返回某些内容的函数都在定义中包含“某些内容”的数据类型(例如:返回 int 值或字符串)。现在,当您的函数没有返回时,将 VOID 视为数据类型(int、string 等)的占位符

回答by zerocool

Think about it this way: if you remove below from your code, do you think your class is of any use:

这样想一下:如果您从代码中删除以下内容,您认为您的课程有任何用处:

public double add1(double n)
    {
        return number = number +  n;
    }

As you are doing calculation, but the result of the calculation is never known to the caller of the API:public void add(double n)

在您进行计算时,API 的调用者永远不知道计算结果:public void add(double n)