Void and return in Java - when to use

后端 未结 7 1938
予麋鹿
予麋鹿 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 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.

提交回复
热议问题