java retain information in recursive function

后端 未结 8 1949
滥情空心
滥情空心 2020-12-29 09:05

Is it possible to retain information via a helper function with java, without using static variables.

For example,

public void foo(){
    int v = 0;
         


        
8条回答
  •  春和景丽
    2020-12-29 09:37

    A variable declared in a scope (for example method) is accessible only in this scope (e.g. not in another method).

    If the information is relevant for the method only, keep the variable in the method. If the information is relevant for the whole object / class state, keep it a class member (static/non static).

    For example:

    public void someRecursiveMethod(int num) {
        while (num < 10) {
            num++;
            someRecursiveMethod(num);
            System.out.println("Current num = " + num);
        }
    }
    

提交回复
热议问题