能不能詳細解釋下為什麼最後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("赵六");
}
}