首頁  >  問答  >  主體

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 天前411

全部回覆(3)我來回復

  • 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

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

    回覆
    0
  • 天蓬老师

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

    那是,你引用的全是y的空間位址

    回覆
    0
  • 取消回覆