我有以下snipet代码:
class Phone {
String phoneNumber = "123456789";
void setNumber () {
String phoneNumber;
phoneNumber = "987654321";
}
}
class TestPhone {
public static void main(String[] args) {
Phone p1 = new Phone();
p1.setNumber();
System.out.println (p1.phoneNumber);
}
}
Run Code Online (Sandbox Code Playgroud)
我期待"987654321"作为结果,但我得到"123456789"它就像方法setNumber没有任何影响任何人都可以帮助我理解请
您在方法中重新声明phoneNumber变量,遮蔽类中的字段,因此在阴影类字段中将看不到对局部变量所做的任何更改.不要这样做; 摆脱重复变量声明,以便在该字段中看到该方法内所做的更改.
例如,改变这个:
void setNumber () {
String phoneNumber; // *** this is a local variable, visible ONLY in the method!
phoneNumber = "987654321"; // this has no effect on the field
}
Run Code Online (Sandbox Code Playgroud)
对此:
void setNumber () {
// String phoneNumber;
phoneNumber = "987654321"; // this will change the field!
}
Run Code Online (Sandbox Code Playgroud)