Java 类对象的引用

49 阅读1分钟

我们把 Students 类 new 一个对象 s1 ,并且给其属性 name 赋值

Students s1 = new Students();
s1.name = "hi";
System.out.println("修改前s1.name的值为:" + s1.name);

然后将对象 s2 赋给 s2 ,并且修改 s2的属性值

Students s2 = s1;
s2.name = "hello";
System.out.println("修改后s2.name的值为:" + s2.name);
System.out.println("修改后s1.name的值为:" + s1.name);

运行代码,查看属性前后的变化

修改前s1.name的值为:hi
修改后s2.name的值为:hello
修改后s1.name的值为:hello

结论

修改了s2的name值,s2的属性值变为新的值"hello",

因为s1和s2是一个对象,所以s1的值也随之变化,由原来的"hi"变为"hello"。