Heim  >  Fragen und Antworten  >  Hauptteil

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]
天蓬老师天蓬老师2742 Tage vor398

Antworte allen(3)Ich werde antworten

  • ringa_lee

    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

    Antwort
    0
  • 阿神

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

    google 值传递和引用传递

    思考问题:最后输出结果是什么?

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

    Antwort
    0
  • 天蓬老师

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

    那是,你引用的全是y的空间地址

    Antwort
    0
  • StornierenAntwort