能不能详细解释下为什么最后y会随着x的变化而变化
Point x = new Point(0,0);
Point y = new Point(1,1);
x = y;
x.setLocation(5,5);
System.out.println("x is :"+x);
System.out.println("y is :"+y);
程序运行结果:
x is java.awt.Point[x=5, y=5]
y is java.awt.Point[x=5, y=5]
ringa_lee2017-04-18 10:56:28
The x and y variables exist in the stack, pointing to the two objects in the heap, new Point(0,0) and new Point(1,1) respectively. Execute x = y,x to point the reference to the address in y memory, x .setLocation(5,5), directly modifies y. Finally, both x and y point to y in the heap, so what is printed is the modified content of x, x=5, y=5
阿神2017-04-18 10:56:28
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
User u = new User("张三");
changeUser(u);
System.out.println(u.getName());
}
public static void changeUser(User user){
user.setName("李四");
user = new User("王五");
user.setName("赵六");
}
}