在Java中,对象是引用类型的,如果将一个对象赋值给另一个同类对象,这两个对象指向同一个内存地址,即只是把内存地址赋值了而已。
例子:
定义一个只含有成员变量的Student类
public class Student { String name; int age; }
s1和s2都是new出来的对象,他们在堆中都开辟了自己的内存空间,并且指向他们的内存地址
但是s3是由s1直接赋值的,实际上是将s1的内存地址赋值给了s3,即他们指向的是同一个地址
当我们把s3发生改变时,s1也会发生改变
public class Demo { public static void main(String[] args) { Student s1 = new Student(); s1.age = 12; s1.name = "simple"; System.out.println("s1: "+s1.age + " " + s1.name); Student s2 = new Student(); s2.age = 20; s2.name = "knight"; System.out.println("s1: "+s1.age + " " + s1.name); System.out.println("s2: "+s2.age + " " + s2.name); Student s3 = s1; s3.age = 88; s3.name = "simpleknight"; System.out.println("s1: "+s1.age + " " + s1.name); System.out.println("s3: "+s3.age + " " + s3.name); } }
结果如图所示