java - 关于引用对象的问题
天蓬老师
天蓬老师 2017-04-18 10:54:28
0
3
400

能不能详细解释下为什么最后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]
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
左手右手慢动作

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

阿神

google pass by value and pass by reference

Question to think about: What is the final output?

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("赵六");
    }
}
Peter_Zhu

That is, all you quoted are the space addresses of y

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!