public class incrementer {
public incrementer () {
counter =1;
}
public incrementer (int startValue) {
counter = startValue;
}
public int nextValue() {
int temp = counter;
counter++;
return (temp);
}
private int counter;
}
import acm.program.*;
public class useCounter extends ConsoleProgram {
public void run() {
incrementer count1 = new incrementer();
incrementer count2 = new incrementer(1000);
println("Five values for count1 :");
countFiveTimes(count1);
println("Five values for count2 :");
countFiveTimes(count2);
println("Another five values for count1 :");
countFiveTimes(count1);
}
private void countFiveTimes(incrementer counter) {
for (int i=0; i<5; i++) {
println(counter.nextValue());
}
}
}
I just learned about the concept of passing objects as parameters in a method call. From my understanding, a run of the useCounter class looks like this:
create count1 = incrementer object with counter value 1
call countFiveTimes method with parameter count1
counter = incrementer object with counter value 1 //assign new name to the object to use it inside the countFiveTimes method//
call nextvalue method with the object(counter at this point, previously count1) and println the return value 5 times.
(first run)
temp = 1;
counter = 2;
return temp
println(temp);
prints 1
(second run)
temp = 2;
counter = 3;
returm temp
println(temp)
prints 2
.... and so on and so forth.
I will skip the count2 part because it isn't relevant to my question.
When the run gets to the println("another 5 values for count1 :"); part, I would normally expect the a run of this part of the class to be the exact same as the first part; that is, I would expect the results to be 1 2 3 4 5 because I do not see the code that is assigning a new value to the counter1 object.(I expect it to be in the same state it was in when I created it)
The explanation my instructor gave was that when you pass on an object as a parameter in a method call, you are essentially passing on the object itself, not a copy of the object.
I feel okay with the concept, but the question is: Where is the new state of the object saved?
Is it in the useCounter class? if it is, where in it?
Help would be much appreciated, sorry for any confusions I might have caused in my question.
EDIT: Result of the run Five values for count1 : 1 2 3 4 5 Five values for count2 : 1000 1001 1002 1003 1004 Another five values for count1 : 6 7 8 9 10
EXPECTED result of the run
Five values for count1 : 1 2 3 4 5 Five values for count2 : 1000 1001 1002 1003 1004 Another five values for count1 : 1 2 3 4 5
Question: I am assuming that the state of the object (count1) is saved after the first five values. Where is it saved? How is it saved when there is no code functioning to save it?