全局变量与方法内的局部变量重名时,方法内的局部变量会覆盖全局变量从而输出Hello,如需输出Hi,使用this关键字即可
public class Test2 {
String str = new String("Hi!");
public void change (String str){
str = "Hello";
System.out.println(this.str);
}
public static void main(String[] args) {
Test2 t2 = new Test2();
t2.change(t2.str);
}
}
t2调用的方法给 str 重新赋值了,输出的当然是重新赋的值
这应该是因为Hi被改成了Hello吧?
你调用了change()方法,传了一个字符串,然后调用change(),随便穿个字符串都会改成hello!