Return of method



  • In carrying out various assignments, there has been one issue that has not yet been understood. May there be a method for finding a field on the number "a" (e.g. chislo field):

    public void proizvedenie(int a){
        chislo = chislo * a;
    }
    

    And the same method:

    public int proizvedenie(int a){
        int proiz = chislo * a;
        return proiz;
    } 
    

    In the end, I'll get the same result. In the first case, the method does not return any value different from the whole in the second case, but if I use the first method, I will have the same effect as the second. What do you mean, "no returns any meaning" and what difference does it make between two cases, just in structure?



  • In this method

    public void proizvedenie(int a){
    chislo = chislo * a;
    }
    

    Class member changed chislo♪ I mean, after the method was followed, the value of a member of the class chislo It'll change.

    This method

    public int proizvedenie(int a){
    int proiz = chislo * a;
    return proiz;
    } 
    

    does not change the meaning of a member chislo♪ After this method, the class member ' s value chislo It'll be the same as before the method called. This method only sets the local variable value proizthe value of which returns from function.

    So these two methods are not equivalent.

    You could write the method as follows:

    public int proizvedenie(int a){
        return chislo = chislo * a;
    }
    

    In this case, not only changes in the value of a member of the class chislobut also returns his new meaning. Such an approach is convenient when the challenge of the method is desirable to link in chains with other problems of methods or functions, such as the withdrawal of a new console.

    Another approach is to restore the previous meaning of a data member

    public int proizvedenie(int a){
        int old_value = chislo;
        chislo = chislo * a;
        return old_value;
    }
    

    But anyway, the meaning of a class member. chislo both methods change.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2