能不能详细解释下为什么最后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
x和y变量存在栈中,分别指向new Point(0,0)和new Point(1,1)这两个堆中的对象,执行x = y,x把引用指向y内存中的地址,x.setLocation(5,5),直接对y进行了修改,最后x和y都指向堆中的y,所以打印的都是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("赵六");
}
}