I think you are looking at this wrong. If you call two methods. eg.
public int test() {
int x = getSomeInt(1);
int y = getSomeInt(2);
return x + y;
}
Are you ever questioning whether return x + y
is done or if the value of x
is determined before y
? It does it from top to bottom and the statement setting y
does not start before getSomeInt(1)
has returned and its value set as x
.
So to your example:
protected int getArea() {
if (width <= 0) {
return 0;
} elseif (width == 1) {
return 1;
} else {
Triangle t2 = new Triangle(width - 1);
int area = t2.getArea();
return area + width;
}
}
So if you have a Triangle with width 1
and call getArea
you get 1
back.
What happens if you do it on a Triangle with width 2
? Well it creates t2
with width 1
and call getArea
on it. We already know the result since we calculated it already. area
becomes 1
and then it returns 1 + 2
.
What happens if you do it with width 3?. It will create t2
with width 2
and call getArea()
on that. We know that returns 3
from the above and the result is 3 + 3
.
The recusive method gets called with a high with
, but it is the one with 1
that gets determined first, then 2, 3, 4, ...and finally the call you actually called has some area
that it adds its with
to.
Each call to a methoid has nothing to do with the callee. It is the same code yes, but it's a different object and the local variables are unique to the call just as the two calls getSomeInt
also have two differen versions of whatever it called its first parameter. They are not entangled unless you are mutating or passing by reference.
Calling a method on an object is very similar to the object being an argument in the call. The recursive call has an object with a smaller width
and at one point it will hit the base case. You could say this is the same:
public static int getArea(Triangle t) {
if (t.width <= 0) {
return 0;
} elseif (t.width == 1) {
return 1;
} else {
Triangle t2 = new Triangle(t.width - 1);
int area = getArea(t2);
return area + t.width;
}
}
Again.. a method being recusive does not change anything. It ahs no special treatment. It needs its calls to finish before it can return the value, just like if you used a different method to get the area in getArea
.. No difference at all.