Method call recursively

I am having trouble moving my head around recursion, more specifically the syntax presented in my tutorial. It looks like this:

public int sum (int num)
{
    int result;

    if (num == 1)
        result =1;
    else
        result = num +sum(num -1);
    return result;
}

I am confused specifically with the line:

result = num + sum(num - 1);

The part that turns me off is every time in any other program, we call methods in one of two ways. Any method is a static method and is called through the name of the class, followed by a period, followed by the name of the method. (Example: Math.random ();) Or, the method was called through an object reference variable that has the same class. (Which we must first create independently) This syntax does not seem to correspond to either of the two previous examples, and I was wondering why this is so? Is it simply because we call the method from the method itself and syntactically how it is executed, or am I missing something?

+4
source share
3 answers

- , invoker , . , Java , , - , , invoker. , .

, , , 1, 3- , 7. , , 7- .

+3

, , this. , :

public int sum (int num) {
    int result;

    if (num == 1)
        result =1;
    else
        result = num + this.sum(num -1);
    return result;
}

, , ( - ).

+3

Java , - . :

- "" , / ( ).

- , , Java: self, , :

Foo a = new Foo();
a.bar();  // calls method bar from class Foo with a instance

Now that you are inside a static or non-static method, you have a class of the surrounding class, which means that you can use other members of the class without adding selfor ClassName.

0
source

Source: https://habr.com/ru/post/1684266/


All Articles