Void and return in Java - when to use

后端 未结 7 1891
予麋鹿
予麋鹿 2020-12-18 17:10

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 re

相关标签:
7条回答
  • 2020-12-18 17:44

    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)

    0 讨论(0)
  • 2020-12-18 17:53

    Do you want to be able to write this?

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

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

    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.

    0 讨论(0)
  • 2020-12-18 17:54

    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.

    0 讨论(0)
  • 2020-12-18 17:58

    return should 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:

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

    0 讨论(0)
  • 2020-12-18 18:01

    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)

    0 讨论(0)
  • 2020-12-18 18:03

    This method :

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

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

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

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

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

    0 讨论(0)
提交回复
热议问题