So I was testing some code and here they are:
public class Phone {
String phoneNumber = "1234";
void setNumber(){
String phoneNumber;
phoneNumber = "4321";
}
}
public class TestPhone {
public static void main(String[] args) {
// TODO Auto-generated method stub
Phone p1 = new Phone();
p1.setNumber();
System.out.println(p1.phoneNumber);
}
}
Output:
1234
Why not 4321
? I called setNumber
so phoneNumber
should be assigned to 4321
, what am I missing?
The local variable phoneNumber
shadows the instance variable with the same name.
void setNumber(){ String phoneNumber; phoneNumber = "4321"; }
So this code sets the local variable, doesn't change the instance variable.
If you wanted to change the instance variable, you would have to disambiguate,
using the this.
prefix, like this:
void setNumber(){
String phoneNumber;
this.phoneNumber = "4321";
}
... or better yet, just remove the pointless local variable entirely... (like you said @RobP!)