I am new to programming and Java and I have some confusion regarding the behavior of global variables in methods of the same class. In an exercise question provided by the course I am taking, I am asked what is the value of variable b after executing inc(b)
.
int b;
int inc(int b){
b++;
return b;
}
b = 5;
inc(b);
The answer is 5, rather than 6, which I understand is because Java is pass by value and all the arguments in the method inc
is simply forgotten afterwards.
On the other hand, in a java class it is recommended to write set and get methods for all the instance variables. Then my question is, why is the setter able to change the instance variable and maintain its value outside the setter? In other words, why is the variable change "forgotten" in the above example, but "remembered" in a set method?
public void setName ( String n ) {
name = n;
}
In other words, why is the variable change "forgotten" in the above example, but "remembered" in a set method?
In your inc
method, you're not changing the field called b
at all. You've got a parameter called b
, so every time the code refers to b
within the method, it refers to the parameter instead of the field. This is called shadowing. If you change it to:
int b;
int inc(int b) {
this.b++;
return this.b;
}
... then the parameter will be ignored, and it will increment the field instead.
Basically, you need to think about what you want the inc
method to do:
See more on this question at Stackoverflow