Reputation: 41
I'm having trouble wrapping my head around recursion, more specifically the syntax provided in my textbook. 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'm confused specifically with the line:
result = num + sum(num - 1);
The part that keeps tripping me up is every time in any other program, we've invoked methods from one of two ways. Either the method is a static method and is invoked through the class name followed by a period, followed by the method name. (Example: Math.random();) Or, the method has been called through an object reference variable which is of the same class. (Which we first have to create independently) This syntax seems to not follow any of the two previous examples and I was wondering why that is? Is it simply because we are invoking the method from within the method itself and that is syntactically how it is accomplished or am I missing something?
Upvotes: 4
Views: 246
Reputation: 3430
A method can be invoked through its name without any dots or imports if the invoker is within the same class as the method. This is because Java only uses dots to navigate to the class location of the method, but if the method is invoked without any dots, than the program will know that the method is within the invoker's class. You can use this method of invoking for all types of methods so long as they are within the same class or superclass.
Take area codes for example. When you dial a number on your phone, you will dial a 1 followed by a 3 digit area code, then a 7 digit number. But if your phone is registered within the 3 digit area code of the number you are dialing, than you only have to type the 7 digit number without the area code.
Upvotes: 3
Reputation: 348
In Java, you cannot place function outside class so you are somehow forced to write it inside a class. Now, you have two types of methods:
Static - you can treat it like 'free' functions placed inside container/namespace (class is the container in this case).
Non-static - this is methods which have a special parameter passed by Java: self
which contains instance data, for example:
Foo a = new Foo();
a.bar(); // calls method bar from class Foo with a instance
Now, when you are inside a static or non-static method you have a scope of surrounding class which means that you can use other class members without adding self
or ClassName
.
Upvotes: 0
Reputation: 2540
When a method is called simply by its name and is not static, it is implied that you are invoking the method on this
. So, your code is equivalent to the following:
public int sum (int num) {
int result;
if (num == 1)
result =1;
else
result = num + this.sum(num -1);
return result;
}
This is true for any instance method defined for a class, not just recursive methods (which aren't syntactically special in any particular way).
Upvotes: 3