Home  >  Q&A  >  body text

java - 关于引用对象的问题

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

reply all(3)I'll reply

  • ringa_lee

    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

    reply
    0
  • 阿神

    阿神2017-04-18 10:56:28

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

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:56:28

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

    reply
    0
  • Cancelreply